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
273,844
<p>How do I add a custom post type to what I'm assuming is a table in WP's underlying database.</p> <p>I.e. I don't want to have this loading on every page and I want to be able to use slug and post-type queries on it.</p> <pre><code>function cptui_register_my_cpts_app() { $labels = array(); $args = array(); register_post_type( "app", $args ); } add_action( 'init', 'cptui_register_my_cpts_app' ); </code></pre> <p>More specifically, I want to be able to create a redirect from a custom post type (in this case 'app') to the login page if members are not already logged in.</p> <pre><code>function my_redirect() { if( !is_user_logged_in() &amp;&amp; is_singular('app') ) { wp_redirect( 'login page' ); exit(); } } add_action('init', 'my_redirect'); </code></pre>
[ { "answer_id": 273828, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>Your function <code>get_instance</code> will never create an instance of the class because of this line:</p>\n\n<pre><code>$instance = new static();\n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>$instance = new VBWpdb();\n</code></pre>\n" }, { "answer_id": 273831, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>You are just doing it wrong. The problem starts with using a singleton, just never do it.</p>\n\n<p>You have a class of loggers which logs into some internal buffer. All loggers log into the same buffer, therefor the buffer (<code>trace</code> in your case) a static array in the class.\nNo more <code>get_intance</code>, just instantiate a new logger and log. This gives you the added flexibility of having several classes of loggers that \"output\" to the same buffer.</p>\n\n<p>We are left with a question of how to inspect the log, and this you do with a static method.</p>\n\n<p>I am sure this scheme can be improved by people that are more hard core OOP than me, using singleton is equivalent to using a <code>namespace</code> and code written under a namespace is easier to read and use than the singleton, just call a function directly with no need to handle the complications of getting an object first, it is easier to use a function in a hook, etc.</p>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124145/" ]
How do I add a custom post type to what I'm assuming is a table in WP's underlying database. I.e. I don't want to have this loading on every page and I want to be able to use slug and post-type queries on it. ``` function cptui_register_my_cpts_app() { $labels = array(); $args = array(); register_post_type( "app", $args ); } add_action( 'init', 'cptui_register_my_cpts_app' ); ``` More specifically, I want to be able to create a redirect from a custom post type (in this case 'app') to the login page if members are not already logged in. ``` function my_redirect() { if( !is_user_logged_in() && is_singular('app') ) { wp_redirect( 'login page' ); exit(); } } add_action('init', 'my_redirect'); ```
You are just doing it wrong. The problem starts with using a singleton, just never do it. You have a class of loggers which logs into some internal buffer. All loggers log into the same buffer, therefor the buffer (`trace` in your case) a static array in the class. No more `get_intance`, just instantiate a new logger and log. This gives you the added flexibility of having several classes of loggers that "output" to the same buffer. We are left with a question of how to inspect the log, and this you do with a static method. I am sure this scheme can be improved by people that are more hard core OOP than me, using singleton is equivalent to using a `namespace` and code written under a namespace is easier to read and use than the singleton, just call a function directly with no need to handle the complications of getting an object first, it is easier to use a function in a hook, etc.
273,870
<p>I have develop a wordpress website consulting and I have different user role </p> <p>and I want to have different content according to user role </p> <p>so I have a landing page with authentification and according the user role login , the homepage is different </p> <p>so I would like to say if plugin who make something like this exist or if can code for that</p> <p>so recap :</p> <p>Home page for not login is landing page home page for user login is different according to user role </p> <p>Thanks !</p>
[ { "answer_id": 273872, "author": "danbrellis", "author_id": 34540, "author_profile": "https://wordpress.stackexchange.com/users/34540", "pm_score": 1, "selected": false, "text": "<p>Two options come to mind. Which one will depend on how different your content is for logged in/not logged in.</p>\n\n<p>1) The first, you can just use IF statements on the homepage template.</p>\n\n<pre><code>$current_user = wp_get_current_user();\n$user = new WP_User( $current_user -&gt;ID);\n\nif($user &amp;&amp; in_array('my-role', $user-&gt;roles)){\n //stuff specific to users with 'my-role'\n}\n.\n.\n.\nelse{\n //stuff for non logged in users or ones that don't match any of your roles\n}\n</code></pre>\n\n<p>2) The second option is to filter the template based on their role. You can hook into the <code>template_include</code> filter. See the examples in the codex: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include</a>. With this option you could have multiple templates for various users and use a different one dynamically if you keep consistent with a template naming convention.</p>\n\n<p>Hopefully this helps. Depending on which option you take I can help provide some more detailed code examples.</p>\n\n<p><strong>UPDATED</strong></p>\n\n<p>Based on the information in your comments, here is an example using the <code>template_include</code> filter hook. You can put this in your functions.php. Untested code:</p>\n\n<pre><code>function wpse_273872_template_include($template) {\n //if user is not logged in, just return and show the default homepage\n if(!is_user_logged_in()) return $template;\n\n $new_template = '';\n $current_user = wp_get_current_user();\n $user = new WP_User( $current_user-&gt;ID);\n\n if(in_array('candidate', $user-&gt;roles)){ //assuming the role name is candidate\n $new_template = locate_template( array( 'homepage-candidate.php' ) );\n }\n elseif(in_array('company', $user-&gt;roles)){ //assuming the role name is company\n $new_template = locate_template( array( 'homepage-company.php' ) );\n }\n if ( '' != $new_template ) {\n $template = $new_template;\n }\n return $template;\n}\nadd_filter( 'template_include', 'wpse_273872_template_include' );\n</code></pre>\n\n<p>The homepage-candidate.php and homepage-company.php are template files that reside in your theme's folder. Here is an example of the file structure:</p>\n\n<pre><code>- my-custom-theme\n |- style.css\n |- functions.php\n |- frontpage.php\n |- homepage-candidate.php\n |- homepage-company.php\n</code></pre>\n" }, { "answer_id": 273880, "author": "ouanounou", "author_id": 124159, "author_profile": "https://wordpress.stackexchange.com/users/124159", "pm_score": 0, "selected": false, "text": "<p>i have create my page directly in wordpress like this \n<a href=\"https://i.stack.imgur.com/hTX3Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hTX3Z.png\" alt=\"enter image description here\"></a></p>\n\n<p>so I have now just one home page in my file template call index.php </p>\n\n<p>and my 2 page is not in this file</p>\n" }, { "answer_id": 273889, "author": "danbrellis", "author_id": 34540, "author_profile": "https://wordpress.stackexchange.com/users/34540", "pm_score": 1, "selected": true, "text": "<p>To use a different page's content on the homepage based on a logged-in user's role you can do this:</p>\n\n<p>In your functions.php file add this code:</p>\n\n<pre><code>function wpse_273872_pre_get_posts( $query ) {\n if ( $query-&gt;is_main_query() &amp;&amp; is_user_logged_in() ) {\n //work-around for using is_front_page() in pre_get_posts\n //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790\n $front_page_id = get_option('page_on_front');\n $current_page_id = $query-&gt;get('page_id');\n $is_static_front_page = 'page' == get_option('show_on_front');\n\n if ($is_static_front_page &amp;&amp; $front_page_id == $current_page_id) {\n $current_user = wp_get_current_user();\n $user = new WP_User($current_user-&gt;ID);\n if (in_array('cs_candidate', $user-&gt;roles)) { //assuming the role name is cs_candidate\n $query-&gt;set('page_id', [page-id-for-candidate-homepage]);\n } elseif (in_array('cs_employer', $user-&gt;roles)) { //assuming the role name is cs_employer\n $query-&gt;set('page_id', [page-id-for-employer-homepage]);\n }\n }\n }\n}\nadd_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' );\n</code></pre>\n\n<p>What this does is:</p>\n\n<ol>\n<li>Filters the wp_query args if a user is logged in, you're on the homepage and it's the main query</li>\n<li>If the user has the role 'candidate', set the post id (p) to the ID of the page you created and change the post_type to 'page'</li>\n<li>Similarily, if the user has a role employer, use the ID for that page.</li>\n</ol>\n\n<p>Thanks for helping clarify all your points.</p>\n" }, { "answer_id": 402827, "author": "Christa Coetser", "author_id": 219361, "author_profile": "https://wordpress.stackexchange.com/users/219361", "pm_score": 0, "selected": false, "text": "<p>I use Gravity Forms and with the User Registration, I have a custom field, &quot;UserType2&quot;.\nDepending on the UserType2 variable in the MySQL UserMeta Table I give different access to Fields on my Gravity Form linked to my Homepage with Conditional Logic.\nThen I can have as many as I want.</p>\n<p>This way I don't need to change anything on the PHP files.</p>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124159/" ]
I have develop a wordpress website consulting and I have different user role and I want to have different content according to user role so I have a landing page with authentification and according the user role login , the homepage is different so I would like to say if plugin who make something like this exist or if can code for that so recap : Home page for not login is landing page home page for user login is different according to user role Thanks !
To use a different page's content on the homepage based on a logged-in user's role you can do this: In your functions.php file add this code: ``` function wpse_273872_pre_get_posts( $query ) { if ( $query->is_main_query() && is_user_logged_in() ) { //work-around for using is_front_page() in pre_get_posts //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790 $front_page_id = get_option('page_on_front'); $current_page_id = $query->get('page_id'); $is_static_front_page = 'page' == get_option('show_on_front'); if ($is_static_front_page && $front_page_id == $current_page_id) { $current_user = wp_get_current_user(); $user = new WP_User($current_user->ID); if (in_array('cs_candidate', $user->roles)) { //assuming the role name is cs_candidate $query->set('page_id', [page-id-for-candidate-homepage]); } elseif (in_array('cs_employer', $user->roles)) { //assuming the role name is cs_employer $query->set('page_id', [page-id-for-employer-homepage]); } } } } add_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' ); ``` What this does is: 1. Filters the wp\_query args if a user is logged in, you're on the homepage and it's the main query 2. If the user has the role 'candidate', set the post id (p) to the ID of the page you created and change the post\_type to 'page' 3. Similarily, if the user has a role employer, use the ID for that page. Thanks for helping clarify all your points.
273,878
<p>I created some code to return attachment categories, that looks like:</p> <pre><code>&lt;?php // Attachment Categories $categories = get_the_category($attachment-&gt;ID); if ($categories) { ?&gt; &lt;ul&gt; &lt;?php foreach ($categories as $category) { ?&gt; &lt;?php if ($category-&gt;name !== 'Slides') if ($category-&gt;name !== 'Uncategorized') { ?&gt; &lt;li&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/li&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;?php } ?&gt; </code></pre> <p>I am trying to add an <code>else</code>, but for some reason the else doesn't work with the two <code>if</code> statements...if I remove one <code>if</code> statement, the <code>else</code> works.</p> <p>The code with the <code>else</code> looks like:</p> <pre><code>&lt;ul&gt; &lt;?php foreach ($categories as $category) { ?&gt; &lt;?php if ($category-&gt;name !== 'Slides') if ($category-&gt;name !== 'Uncategorized') { ?&gt; &lt;li&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/li&gt; &lt;?php } else { ?&gt; &lt;li&gt;Unknown&lt;/li&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/ul&gt; </code></pre> <p>Can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 273872, "author": "danbrellis", "author_id": 34540, "author_profile": "https://wordpress.stackexchange.com/users/34540", "pm_score": 1, "selected": false, "text": "<p>Two options come to mind. Which one will depend on how different your content is for logged in/not logged in.</p>\n\n<p>1) The first, you can just use IF statements on the homepage template.</p>\n\n<pre><code>$current_user = wp_get_current_user();\n$user = new WP_User( $current_user -&gt;ID);\n\nif($user &amp;&amp; in_array('my-role', $user-&gt;roles)){\n //stuff specific to users with 'my-role'\n}\n.\n.\n.\nelse{\n //stuff for non logged in users or ones that don't match any of your roles\n}\n</code></pre>\n\n<p>2) The second option is to filter the template based on their role. You can hook into the <code>template_include</code> filter. See the examples in the codex: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include</a>. With this option you could have multiple templates for various users and use a different one dynamically if you keep consistent with a template naming convention.</p>\n\n<p>Hopefully this helps. Depending on which option you take I can help provide some more detailed code examples.</p>\n\n<p><strong>UPDATED</strong></p>\n\n<p>Based on the information in your comments, here is an example using the <code>template_include</code> filter hook. You can put this in your functions.php. Untested code:</p>\n\n<pre><code>function wpse_273872_template_include($template) {\n //if user is not logged in, just return and show the default homepage\n if(!is_user_logged_in()) return $template;\n\n $new_template = '';\n $current_user = wp_get_current_user();\n $user = new WP_User( $current_user-&gt;ID);\n\n if(in_array('candidate', $user-&gt;roles)){ //assuming the role name is candidate\n $new_template = locate_template( array( 'homepage-candidate.php' ) );\n }\n elseif(in_array('company', $user-&gt;roles)){ //assuming the role name is company\n $new_template = locate_template( array( 'homepage-company.php' ) );\n }\n if ( '' != $new_template ) {\n $template = $new_template;\n }\n return $template;\n}\nadd_filter( 'template_include', 'wpse_273872_template_include' );\n</code></pre>\n\n<p>The homepage-candidate.php and homepage-company.php are template files that reside in your theme's folder. Here is an example of the file structure:</p>\n\n<pre><code>- my-custom-theme\n |- style.css\n |- functions.php\n |- frontpage.php\n |- homepage-candidate.php\n |- homepage-company.php\n</code></pre>\n" }, { "answer_id": 273880, "author": "ouanounou", "author_id": 124159, "author_profile": "https://wordpress.stackexchange.com/users/124159", "pm_score": 0, "selected": false, "text": "<p>i have create my page directly in wordpress like this \n<a href=\"https://i.stack.imgur.com/hTX3Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hTX3Z.png\" alt=\"enter image description here\"></a></p>\n\n<p>so I have now just one home page in my file template call index.php </p>\n\n<p>and my 2 page is not in this file</p>\n" }, { "answer_id": 273889, "author": "danbrellis", "author_id": 34540, "author_profile": "https://wordpress.stackexchange.com/users/34540", "pm_score": 1, "selected": true, "text": "<p>To use a different page's content on the homepage based on a logged-in user's role you can do this:</p>\n\n<p>In your functions.php file add this code:</p>\n\n<pre><code>function wpse_273872_pre_get_posts( $query ) {\n if ( $query-&gt;is_main_query() &amp;&amp; is_user_logged_in() ) {\n //work-around for using is_front_page() in pre_get_posts\n //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790\n $front_page_id = get_option('page_on_front');\n $current_page_id = $query-&gt;get('page_id');\n $is_static_front_page = 'page' == get_option('show_on_front');\n\n if ($is_static_front_page &amp;&amp; $front_page_id == $current_page_id) {\n $current_user = wp_get_current_user();\n $user = new WP_User($current_user-&gt;ID);\n if (in_array('cs_candidate', $user-&gt;roles)) { //assuming the role name is cs_candidate\n $query-&gt;set('page_id', [page-id-for-candidate-homepage]);\n } elseif (in_array('cs_employer', $user-&gt;roles)) { //assuming the role name is cs_employer\n $query-&gt;set('page_id', [page-id-for-employer-homepage]);\n }\n }\n }\n}\nadd_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' );\n</code></pre>\n\n<p>What this does is:</p>\n\n<ol>\n<li>Filters the wp_query args if a user is logged in, you're on the homepage and it's the main query</li>\n<li>If the user has the role 'candidate', set the post id (p) to the ID of the page you created and change the post_type to 'page'</li>\n<li>Similarily, if the user has a role employer, use the ID for that page.</li>\n</ol>\n\n<p>Thanks for helping clarify all your points.</p>\n" }, { "answer_id": 402827, "author": "Christa Coetser", "author_id": 219361, "author_profile": "https://wordpress.stackexchange.com/users/219361", "pm_score": 0, "selected": false, "text": "<p>I use Gravity Forms and with the User Registration, I have a custom field, &quot;UserType2&quot;.\nDepending on the UserType2 variable in the MySQL UserMeta Table I give different access to Fields on my Gravity Form linked to my Homepage with Conditional Logic.\nThen I can have as many as I want.</p>\n<p>This way I don't need to change anything on the PHP files.</p>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I created some code to return attachment categories, that looks like: ``` <?php // Attachment Categories $categories = get_the_category($attachment->ID); if ($categories) { ?> <ul> <?php foreach ($categories as $category) { ?> <?php if ($category->name !== 'Slides') if ($category->name !== 'Uncategorized') { ?> <li><?php echo $category->name; ?></li> <?php } ?> <?php } ?> </ul> <?php } ?> ``` I am trying to add an `else`, but for some reason the else doesn't work with the two `if` statements...if I remove one `if` statement, the `else` works. The code with the `else` looks like: ``` <ul> <?php foreach ($categories as $category) { ?> <?php if ($category->name !== 'Slides') if ($category->name !== 'Uncategorized') { ?> <li><?php echo $category->name; ?></li> <?php } else { ?> <li>Unknown</li> <?php } ?> <?php } ?> </ul> ``` Can anyone point me in the right direction? Thanks, Josh
To use a different page's content on the homepage based on a logged-in user's role you can do this: In your functions.php file add this code: ``` function wpse_273872_pre_get_posts( $query ) { if ( $query->is_main_query() && is_user_logged_in() ) { //work-around for using is_front_page() in pre_get_posts //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790 $front_page_id = get_option('page_on_front'); $current_page_id = $query->get('page_id'); $is_static_front_page = 'page' == get_option('show_on_front'); if ($is_static_front_page && $front_page_id == $current_page_id) { $current_user = wp_get_current_user(); $user = new WP_User($current_user->ID); if (in_array('cs_candidate', $user->roles)) { //assuming the role name is cs_candidate $query->set('page_id', [page-id-for-candidate-homepage]); } elseif (in_array('cs_employer', $user->roles)) { //assuming the role name is cs_employer $query->set('page_id', [page-id-for-employer-homepage]); } } } } add_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' ); ``` What this does is: 1. Filters the wp\_query args if a user is logged in, you're on the homepage and it's the main query 2. If the user has the role 'candidate', set the post id (p) to the ID of the page you created and change the post\_type to 'page' 3. Similarily, if the user has a role employer, use the ID for that page. Thanks for helping clarify all your points.
273,907
<p>I would like to write a little script that does a check whenever an order is created in WooCommerce (right after checkout) and then conditionally changes the Shipping Address of the customer.</p> <p>I think I need a filter hook that 'fires' as soon as an order is created. I tried several things in the <a href="https://docs.woocommerce.com/wc-apidocs/hook-docs.html" rel="noreferrer">WooCommerce Hook reference guide</a>, like: 'woocommerce_create_order', but without success. I also contacted WooCommerce support, but no solution. I also checked out: <a href="https://wordpress.stackexchange.com/questions/212400/woocommerce-hook-after-creating-order">Woocommerce hook after order (on Stackexchange)</a>, however I would need a filter hook that fires before order create (not after).</p> <p>What I would like to accomplish is something like:</p> <pre><code>function alter_shipping ($order) { if ($something == $condition) { $order-&gt;shipping_address = "..."; //(simplified) } return $order; } add_filter( 'woocommerce_create_order', 'alter_shipping', 10, 1 ); </code></pre> <p>This filter 'woocommerce_create_order' in above example doesn't pass any variables to be manipulated.</p> <p>I need to conditionally manipulate the shipping address in a WooCommerce order as it gets created. Does anyone know a suitable filter hook for this? Or another way?</p>
[ { "answer_id": 309707, "author": "Madebymartin", "author_id": 31520, "author_profile": "https://wordpress.stackexchange.com/users/31520", "pm_score": 4, "selected": true, "text": "<p>Stumbled on this looking for the same thing which I've now figured out (Woocommerce 3.x)...</p>\n\n<pre><code>add_filter( 'woocommerce_checkout_create_order', 'mbm_alter_shipping', 10, 1 );\nfunction mbm_alter_shipping ($order) {\n\n if ($something == $condition) {\n $address = array(\n 'first_name' =&gt; 'Martin',\n 'last_name' =&gt; 'Stevens',\n 'company' =&gt; 'MBM Studio',\n 'email' =&gt; '[email protected]',\n 'phone' =&gt; '777-777-777-777',\n 'address_1' =&gt; '99 Arcadia Avenue',\n 'address_2' =&gt; '', \n 'city' =&gt; 'London',\n 'state' =&gt; '',\n 'postcode' =&gt; '12345',\n 'country' =&gt; 'UK'\n );\n\n $order-&gt;set_address( $address, 'shipping' );\n\n }\n\n return $order;\n\n}\n</code></pre>\n" }, { "answer_id": 309708, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Try action hook <code>woocommerce_checkout_create_order</code>, it is called just before save to DB.</p>\n\n<p><a href=\"https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#334\" rel=\"nofollow noreferrer\">woocommerce_checkout_create_order</a></p>\n" }, { "answer_id": 345504, "author": "RachC", "author_id": 173818, "author_profile": "https://wordpress.stackexchange.com/users/173818", "pm_score": 1, "selected": false, "text": "<p>you got the right filter that arguments are wrong way:</p>\n\n<p><strong>woocommerce 3.0.6 doc</strong></p>\n\n<pre><code>// define the woocommerce_create_order callback \nfunction filter_woocommerce_create_order( $null, $instance ) { \n // make filter magic happen here... \n return $null; \n}; \n\n// add the filter \nadd_filter( 'woocommerce_create_order', 'filter_woocommerce_create_order', 10, 2 ); \n</code></pre>\n\n<p>So your <code>$order</code> would always be null, then put the null replace of your <code>$order</code>, and let <code>$order</code> move to second params. Then return value must be <code>$order_id</code> or the try-catch function would stuck your snippets. There is <a href=\"https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#321\" rel=\"nofollow noreferrer\">full doc</a> of this function.</p>\n\n<p><strong>fixed</strong></p>\n\n<pre><code>function alter_shipping (null,$order) {\n if ($something == $condition) {\n $order-&gt;shipping_address = \"...\"; //(simplified)\n }\n $order_id = $order-&gt;save();\n\n return $order_id;\n}\nadd_filter( 'woocommerce_create_order', 'alter_shipping', 10, 2);\n</code></pre>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86827/" ]
I would like to write a little script that does a check whenever an order is created in WooCommerce (right after checkout) and then conditionally changes the Shipping Address of the customer. I think I need a filter hook that 'fires' as soon as an order is created. I tried several things in the [WooCommerce Hook reference guide](https://docs.woocommerce.com/wc-apidocs/hook-docs.html), like: 'woocommerce\_create\_order', but without success. I also contacted WooCommerce support, but no solution. I also checked out: [Woocommerce hook after order (on Stackexchange)](https://wordpress.stackexchange.com/questions/212400/woocommerce-hook-after-creating-order), however I would need a filter hook that fires before order create (not after). What I would like to accomplish is something like: ``` function alter_shipping ($order) { if ($something == $condition) { $order->shipping_address = "..."; //(simplified) } return $order; } add_filter( 'woocommerce_create_order', 'alter_shipping', 10, 1 ); ``` This filter 'woocommerce\_create\_order' in above example doesn't pass any variables to be manipulated. I need to conditionally manipulate the shipping address in a WooCommerce order as it gets created. Does anyone know a suitable filter hook for this? Or another way?
Stumbled on this looking for the same thing which I've now figured out (Woocommerce 3.x)... ``` add_filter( 'woocommerce_checkout_create_order', 'mbm_alter_shipping', 10, 1 ); function mbm_alter_shipping ($order) { if ($something == $condition) { $address = array( 'first_name' => 'Martin', 'last_name' => 'Stevens', 'company' => 'MBM Studio', 'email' => '[email protected]', 'phone' => '777-777-777-777', 'address_1' => '99 Arcadia Avenue', 'address_2' => '', 'city' => 'London', 'state' => '', 'postcode' => '12345', 'country' => 'UK' ); $order->set_address( $address, 'shipping' ); } return $order; } ```
273,910
<p>I have followed the solution given <a href="https://wordpress.stackexchange.com/questions/58932/how-do-i-remove-a-pre-existing-customizer-setting">here</a> by Krupal Patel.</p> <pre><code>add_action( "customize_register", "ruth_sherman_theme_customize_register" ); function ruth_sherman_theme_customize_register( $wp_customize ) { //============================================================= // Remove header image and widgets option from theme customizer //============================================================= $wp_customize-&gt;remove_control( "header_image" ); $wp_customize-&gt;remove_panel( "widgets" ); //============================================================= // Remove Colors, Background image, and Static front page // option from theme customizer //============================================================= $wp_customize-&gt;remove_section( "colors" ); $wp_customize-&gt;remove_section( "background_image" ); $wp_customize-&gt;remove_section( "static_front_page" ); } </code></pre> <p>But I am unable to remove "Theme Options", "Menus" and "Header Media". Any help?</p> <p>I am working on Twenty Seventeen.</p>
[ { "answer_id": 273921, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 2, "selected": false, "text": "<p>The first thing to try is to increase the priority of your <code>customize_register</code> action from the default of <code>10</code> to something like <code>100</code>. The reason for this is other components add their sections and controls in the same action and some after <code>10</code>, so the things you are trying to remove may simply not have been added yet.</p>\n\n<p>The second thing to note is that Widgets and Menus are a special case and they should not be disabled in this way. Instead, there is a dedicated filter you use to prevent them from getting loaded:</p>\n\n<pre><code>add_filter( 'customize_loaded_components', '__return_empty_array' );\n</code></pre>\n\n<p>For more see the <a href=\"https://developer.wordpress.org/reference/hooks/customize_loaded_components/\" rel=\"nofollow noreferrer\">hook docs</a>.</p>\n\n<p>See also my post on how to <a href=\"https://make.xwp.co/2016/09/11/resetting-the-customizer-to-a-blank-slate/\" rel=\"nofollow noreferrer\">reset the Customizer to a blank slate</a>.</p>\n" }, { "answer_id": 273923, "author": "Digvijayad", "author_id": 118765, "author_profile": "https://wordpress.stackexchange.com/users/118765", "pm_score": 0, "selected": false, "text": "<p>Well besides the answer given by Weston, i tried the following commands. All of them worked except for the menu one. </p>\n\n<pre><code> $wp_customize-&gt;remove_panel(\"nav_menus\");\n $wp_customize-&gt;remove_panel(\"widgets\");\n\n $wp_customize-&gt;remove_section('header_image'); //removes Header Media\n $wp_customize-&gt;remove_section('title');\n\n $wp_customize-&gt;remove_section(\"static_front_page\");\n $wp_customize-&gt;remove_section(\"custom_css\");\n $wp_customize-&gt;remove_section(\"title_tagline\");\n $wp_customize-&gt;remove_section(\"colors\"); \n</code></pre>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4612/" ]
I have followed the solution given [here](https://wordpress.stackexchange.com/questions/58932/how-do-i-remove-a-pre-existing-customizer-setting) by Krupal Patel. ``` add_action( "customize_register", "ruth_sherman_theme_customize_register" ); function ruth_sherman_theme_customize_register( $wp_customize ) { //============================================================= // Remove header image and widgets option from theme customizer //============================================================= $wp_customize->remove_control( "header_image" ); $wp_customize->remove_panel( "widgets" ); //============================================================= // Remove Colors, Background image, and Static front page // option from theme customizer //============================================================= $wp_customize->remove_section( "colors" ); $wp_customize->remove_section( "background_image" ); $wp_customize->remove_section( "static_front_page" ); } ``` But I am unable to remove "Theme Options", "Menus" and "Header Media". Any help? I am working on Twenty Seventeen.
The first thing to try is to increase the priority of your `customize_register` action from the default of `10` to something like `100`. The reason for this is other components add their sections and controls in the same action and some after `10`, so the things you are trying to remove may simply not have been added yet. The second thing to note is that Widgets and Menus are a special case and they should not be disabled in this way. Instead, there is a dedicated filter you use to prevent them from getting loaded: ``` add_filter( 'customize_loaded_components', '__return_empty_array' ); ``` For more see the [hook docs](https://developer.wordpress.org/reference/hooks/customize_loaded_components/). See also my post on how to [reset the Customizer to a blank slate](https://make.xwp.co/2016/09/11/resetting-the-customizer-to-a-blank-slate/).
273,920
<p>I am trying to make one specific page on my wordpress installation to have a different text on the "Upload" button.</p> <p>So i tried:</p> <pre><code>function change_settingspage_publish_button( $translation, $text ) { if ( '567' == get_the_ID() &amp;&amp; $text == 'Publish' ) { return 'Save Settings'; } else { return $translation; } } add_filter( 'gettext', 'change_settingspage_publish_button', 10, 2 ); </code></pre> <p>(Where '567' is the page id). but it doesn't work. any ideas?</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $translation, $text ) {\nif ( 'CUSTOM_POST_TYPE' == get_post_type() &amp;&amp; ($text == 'Publish' || $text == 'Update') ) {\n return 'Save';\n } else {\n return $translation;\n }\n}\n</code></pre>\n" }, { "answer_id": 273939, "author": "mrmadhat", "author_id": 68703, "author_profile": "https://wordpress.stackexchange.com/users/68703", "pm_score": 0, "selected": false, "text": "<p>You can use something like this if you'd like to target a specific post/page ID.</p>\n\n<pre><code>add_action('admin_notices', 'check_id_before_text_change_wpse_273920');\n\nfunction check_id_before_text_change_wpse_273920() {\n global $post;\n //if post isn't set bail\n if(null == $post)\n return;\n\n $id = $post-&gt;ID;\n //add our filter if the id matches\n if($id == '567') {\n add_filter('gettext', 'change_publish_text_wpse_273920', 30, 2);\n }\n}\n\nfunction change_publish_text_wpse_273920($translation, $text) {\n //if this runs and publish isn't in the text\n //we still want to return something\n $rtn_text = $translation;\n\n if($text === 'Publish') {\n $rtn_text = 'Save setting';\n }\n\n return $rtn_text;\n}\n</code></pre>\n" }, { "answer_id": 349531, "author": "oscarmrom", "author_id": 176079, "author_profile": "https://wordpress.stackexchange.com/users/176079", "pm_score": 2, "selected": false, "text": "<p>I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: <a href=\"https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor\">Changing text within the Block Editor</a></p>\n\n<p>Which I applied in my plugin code (you can insert this into your Themes functions.php file, too).</p>\n\n<pre><code>function change_publish_button_text() {\n// Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n}\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n\n<p>Which to your specific request to target only on a post ID you can do this:</p>\n\n<pre><code>function change_publish_button_text() {\n global $post;\n if (get_the_ID() == '123') {\n // Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n }\n }\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124115/" ]
I am trying to make one specific page on my wordpress installation to have a different text on the "Upload" button. So i tried: ``` function change_settingspage_publish_button( $translation, $text ) { if ( '567' == get_the_ID() && $text == 'Publish' ) { return 'Save Settings'; } else { return $translation; } } add_filter( 'gettext', 'change_settingspage_publish_button', 10, 2 ); ``` (Where '567' is the page id). but it doesn't work. any ideas?
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,941
<p>Trying to create a template that places a custom post UI image between the navigation bar and the title like this:</p> <p><a href="https://i.stack.imgur.com/ZuIYa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZuIYa.png" alt="Intended outcome"></a></p> <p>However, I am unable to override the header-extensions.php in my child folder to the parent</p> <p>The page is displayed through single-program.php -> get_header(); -> header-extensions.php -> ambition_headercontent_details();</p> <p>The code that is fit between the Navbar and the title:</p> <pre><code> &lt;/div&gt;&lt;!-- .container --&gt; &lt;img id="single-program-banner" src="&lt;?php the_field('banner'); ?&gt;" alt="" /&gt; &lt;/div&gt;&lt;!-- .hgroup-wrap --&gt; </code></pre> <p>Theme I'm using <a href="https://www.themehorse.com/preview/ambition/" rel="nofollow noreferrer">https://www.themehorse.com/preview/ambition/</a></p> <p>Thank you</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $translation, $text ) {\nif ( 'CUSTOM_POST_TYPE' == get_post_type() &amp;&amp; ($text == 'Publish' || $text == 'Update') ) {\n return 'Save';\n } else {\n return $translation;\n }\n}\n</code></pre>\n" }, { "answer_id": 273939, "author": "mrmadhat", "author_id": 68703, "author_profile": "https://wordpress.stackexchange.com/users/68703", "pm_score": 0, "selected": false, "text": "<p>You can use something like this if you'd like to target a specific post/page ID.</p>\n\n<pre><code>add_action('admin_notices', 'check_id_before_text_change_wpse_273920');\n\nfunction check_id_before_text_change_wpse_273920() {\n global $post;\n //if post isn't set bail\n if(null == $post)\n return;\n\n $id = $post-&gt;ID;\n //add our filter if the id matches\n if($id == '567') {\n add_filter('gettext', 'change_publish_text_wpse_273920', 30, 2);\n }\n}\n\nfunction change_publish_text_wpse_273920($translation, $text) {\n //if this runs and publish isn't in the text\n //we still want to return something\n $rtn_text = $translation;\n\n if($text === 'Publish') {\n $rtn_text = 'Save setting';\n }\n\n return $rtn_text;\n}\n</code></pre>\n" }, { "answer_id": 349531, "author": "oscarmrom", "author_id": 176079, "author_profile": "https://wordpress.stackexchange.com/users/176079", "pm_score": 2, "selected": false, "text": "<p>I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: <a href=\"https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor\">Changing text within the Block Editor</a></p>\n\n<p>Which I applied in my plugin code (you can insert this into your Themes functions.php file, too).</p>\n\n<pre><code>function change_publish_button_text() {\n// Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n}\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n\n<p>Which to your specific request to target only on a post ID you can do this:</p>\n\n<pre><code>function change_publish_button_text() {\n global $post;\n if (get_the_ID() == '123') {\n // Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n }\n }\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n" } ]
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124196/" ]
Trying to create a template that places a custom post UI image between the navigation bar and the title like this: [![Intended outcome](https://i.stack.imgur.com/ZuIYa.png)](https://i.stack.imgur.com/ZuIYa.png) However, I am unable to override the header-extensions.php in my child folder to the parent The page is displayed through single-program.php -> get\_header(); -> header-extensions.php -> ambition\_headercontent\_details(); The code that is fit between the Navbar and the title: ``` </div><!-- .container --> <img id="single-program-banner" src="<?php the_field('banner'); ?>" alt="" /> </div><!-- .hgroup-wrap --> ``` Theme I'm using <https://www.themehorse.com/preview/ambition/> Thank you
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,958
<p>I'm working on a site that uses two different pages to filter lists of posts associated with the same custom post type ("media"), and both pages have their own templates-- a more general page named <code>page-media.php</code> and one that's more narrowly focused via taxonomy, <code>page-music-library.php</code>. While both of these pages filter lists of posts of the "media" custom post type, I would like each to render the posts in a different <code>single-</code> view when the post titles are clicked. For the main <code>page-media.php</code> template, I created a <code>single-media.php</code> template for single post views associated with that page. However, I'm not quite sure how to define an alternate <code>single-</code> view associated with the <code>page-music-library.php</code> template?</p> <p>I'm seeing from <a href="https://wordpress.stackexchange.com/questions/254845/multiple-single-post-templates">this post</a> and elsewhere that as of WP 4.7, "Post Type Templates" can offer more flexibility in this way, but I'm not clear on whether that feature would apply to my situation. Thanks for any insight here, and please let me know if my objective is unclear in any way.</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $translation, $text ) {\nif ( 'CUSTOM_POST_TYPE' == get_post_type() &amp;&amp; ($text == 'Publish' || $text == 'Update') ) {\n return 'Save';\n } else {\n return $translation;\n }\n}\n</code></pre>\n" }, { "answer_id": 273939, "author": "mrmadhat", "author_id": 68703, "author_profile": "https://wordpress.stackexchange.com/users/68703", "pm_score": 0, "selected": false, "text": "<p>You can use something like this if you'd like to target a specific post/page ID.</p>\n\n<pre><code>add_action('admin_notices', 'check_id_before_text_change_wpse_273920');\n\nfunction check_id_before_text_change_wpse_273920() {\n global $post;\n //if post isn't set bail\n if(null == $post)\n return;\n\n $id = $post-&gt;ID;\n //add our filter if the id matches\n if($id == '567') {\n add_filter('gettext', 'change_publish_text_wpse_273920', 30, 2);\n }\n}\n\nfunction change_publish_text_wpse_273920($translation, $text) {\n //if this runs and publish isn't in the text\n //we still want to return something\n $rtn_text = $translation;\n\n if($text === 'Publish') {\n $rtn_text = 'Save setting';\n }\n\n return $rtn_text;\n}\n</code></pre>\n" }, { "answer_id": 349531, "author": "oscarmrom", "author_id": 176079, "author_profile": "https://wordpress.stackexchange.com/users/176079", "pm_score": 2, "selected": false, "text": "<p>I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: <a href=\"https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor\">Changing text within the Block Editor</a></p>\n\n<p>Which I applied in my plugin code (you can insert this into your Themes functions.php file, too).</p>\n\n<pre><code>function change_publish_button_text() {\n// Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n}\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n\n<p>Which to your specific request to target only on a post ID you can do this:</p>\n\n<pre><code>function change_publish_button_text() {\n global $post;\n if (get_the_ID() == '123') {\n // Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n }\n }\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/273958", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89753/" ]
I'm working on a site that uses two different pages to filter lists of posts associated with the same custom post type ("media"), and both pages have their own templates-- a more general page named `page-media.php` and one that's more narrowly focused via taxonomy, `page-music-library.php`. While both of these pages filter lists of posts of the "media" custom post type, I would like each to render the posts in a different `single-` view when the post titles are clicked. For the main `page-media.php` template, I created a `single-media.php` template for single post views associated with that page. However, I'm not quite sure how to define an alternate `single-` view associated with the `page-music-library.php` template? I'm seeing from [this post](https://wordpress.stackexchange.com/questions/254845/multiple-single-post-templates) and elsewhere that as of WP 4.7, "Post Type Templates" can offer more flexibility in this way, but I'm not clear on whether that feature would apply to my situation. Thanks for any insight here, and please let me know if my objective is unclear in any way.
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,977
<p>I'm new to wordpress, and I want to edit the <strong>homepage</strong> of a theme. I just could not find out which file should I be editing with. I've tried to remove <em>page.php</em>, <em>index.php</em>, <em>single.php</em> under /wp-content/themes/mytheme, but my site is still working after I removed all these files, so which file is the theme actually using as the homepage?</p> <p>I'm using wordpress 4.8, wooCommerce 3.1</p> <p>I'm using <strong>Rosa</strong> theme, and the files listed under the theme root are these, index.php, page.php, single.php, sidebar.php, functions.php, footer.php, comments.php header.php</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $translation, $text ) {\nif ( 'CUSTOM_POST_TYPE' == get_post_type() &amp;&amp; ($text == 'Publish' || $text == 'Update') ) {\n return 'Save';\n } else {\n return $translation;\n }\n}\n</code></pre>\n" }, { "answer_id": 273939, "author": "mrmadhat", "author_id": 68703, "author_profile": "https://wordpress.stackexchange.com/users/68703", "pm_score": 0, "selected": false, "text": "<p>You can use something like this if you'd like to target a specific post/page ID.</p>\n\n<pre><code>add_action('admin_notices', 'check_id_before_text_change_wpse_273920');\n\nfunction check_id_before_text_change_wpse_273920() {\n global $post;\n //if post isn't set bail\n if(null == $post)\n return;\n\n $id = $post-&gt;ID;\n //add our filter if the id matches\n if($id == '567') {\n add_filter('gettext', 'change_publish_text_wpse_273920', 30, 2);\n }\n}\n\nfunction change_publish_text_wpse_273920($translation, $text) {\n //if this runs and publish isn't in the text\n //we still want to return something\n $rtn_text = $translation;\n\n if($text === 'Publish') {\n $rtn_text = 'Save setting';\n }\n\n return $rtn_text;\n}\n</code></pre>\n" }, { "answer_id": 349531, "author": "oscarmrom", "author_id": 176079, "author_profile": "https://wordpress.stackexchange.com/users/176079", "pm_score": 2, "selected": false, "text": "<p>I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: <a href=\"https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor\">Changing text within the Block Editor</a></p>\n\n<p>Which I applied in my plugin code (you can insert this into your Themes functions.php file, too).</p>\n\n<pre><code>function change_publish_button_text() {\n// Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n}\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n\n<p>Which to your specific request to target only on a post ID you can do this:</p>\n\n<pre><code>function change_publish_button_text() {\n global $post;\n if (get_the_ID() == '123') {\n // Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?&gt;\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']});\n &lt;/script&gt;\n\n &lt;script&gt;\n wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']});\n &lt;/script&gt;\n &lt;?php\n endif;\n }\n }\n\nadd_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 );\n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/273977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113712/" ]
I'm new to wordpress, and I want to edit the **homepage** of a theme. I just could not find out which file should I be editing with. I've tried to remove *page.php*, *index.php*, *single.php* under /wp-content/themes/mytheme, but my site is still working after I removed all these files, so which file is the theme actually using as the homepage? I'm using wordpress 4.8, wooCommerce 3.1 I'm using **Rosa** theme, and the files listed under the theme root are these, index.php, page.php, single.php, sidebar.php, functions.php, footer.php, comments.php header.php
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,986
<p>I'm having a tough time including jquery-ui scripts and styles in my plugin. It seems that my <code>wp_enqueue_script</code> calls are simply ignored.</p> <p>There are already many questions similar to this one, but all answers I've found so far boil down to call <code>wp_enqueue_script</code> inside the <code>wp_enqueue_scripts</code> action hook, which I'm already doing.</p> <p>In the constructor of my class I call:</p> <pre><code>add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts') ); </code></pre> <p>and then, below:</p> <pre><code>public function enqueue_scripts() { wp_enqueue_script( 'jquery-ui-core', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-widget', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-mouse', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-accordion', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-autocomplete', false, array('jquery')); wp_enqueue_script( 'jquery-ui-slider', false, array('jquery')); </code></pre> <p>I've checked that the code actually gets executed each page load. However the pages lack the <code>&lt;link&gt;</code> tags for the jquery-ui library. I've already tried with and without the <code>jquery</code> dependency explicitly specified in the third argument of the <code>wp_enqueue_script</code> calls.</p> <p>I've also tried with a plain WP 4.8 installation with no plugins installed other than mine, and with the default twenty seventeen theme only. No dice.</p> <p>What's wrong with my code?</p>
[ { "answer_id": 273993, "author": "umesh.nevase", "author_id": 9279, "author_profile": "https://wordpress.stackexchange.com/users/9279", "pm_score": 1, "selected": false, "text": "<p>I've modified your script. try with this, it is working.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts') );\npublic function enqueue_scripts()\n{ \n wp_enqueue_script( 'jquery-ui-core');\n wp_enqueue_script( 'jquery-ui-widget');\n wp_enqueue_script( 'jquery-ui-mouse');\n wp_enqueue_script( 'jquery-ui-accordion' );\n wp_enqueue_script( 'jquery-ui-autocomplete');\n wp_enqueue_script( 'jquery-ui-slider');\n}\n</code></pre>\n" }, { "answer_id": 273996, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 6, "selected": true, "text": "<p>First of all, WordPress registers jQuery UI via <a href=\"https://stackoverflow.com/questions/8849684/wordpress-jquery-ui-css-files\"><code>wp_default_scripts()</code></a>. Dependencies are already set, so you only need to enqueue the script you really need (and not the core). Since you're not changing version number or anything, it is ok to only use the handle.</p>\n<pre><code>// no need to enqueue -core, because dependancies are set\nwp_enqueue_script( 'jquery-ui-widget' );\nwp_enqueue_script( 'jquery-ui-mouse' );\nwp_enqueue_script( 'jquery-ui-accordion' );\nwp_enqueue_script( 'jquery-ui-autocomplete' );\nwp_enqueue_script( 'jquery-ui-slider' );\n</code></pre>\n<p>As for the stylesheets: <strong>WordPress does not register jQuery UI styles by default!</strong></p>\n<p>In the comments, <a href=\"https://wordpress.stackexchange.com/questions/273986/correct-way-to-enqueue-jquery-ui/273996#comment523572_273996\">butlerblog pointed out</a> that according to the <a href=\"https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/#8-plugins-may-not-send-executable-code-via-third-party-systems\" rel=\"noreferrer\">Plugin Guidelines</a></p>\n<blockquote>\n<p>Executing outside code within a plugin when not acting as a service is not allowed, for example:</p>\n<ul>\n<li>Calling third party CDNs for reasons other than font inclusions; all non-service related JavaScript and CSS must be included locally</li>\n</ul>\n</blockquote>\n<p>This means loading the styles via CDN is not permitted and should always be done locally. You can do so by using <code>wp_enqueue_style()</code>.</p>\n" }, { "answer_id": 306129, "author": "Greg Perham", "author_id": 63369, "author_profile": "https://wordpress.stackexchange.com/users/63369", "pm_score": 3, "selected": false, "text": "<p>If you are enqueuing your own script, you can just add <code>'jquery-ui-accordion'</code>, for example, to the list of dependencies. All the required dependencies will be added automatically. Example:</p>\n\n<pre><code>wp_enqueue_script( 'my-theme', get_stylesheet_directory_uri() . '/js/theme.js', array( 'jquery', 'jquery-ui-accordion' ) );\n</code></pre>\n\n<p>Will generate this code:</p>\n\n<pre><code>&lt;script type='text/javascript' src='/wp-includes/js/jquery/ui/core.min.js'&gt;&lt;/script&gt;\n&lt;script type='text/javascript' src='/wp-includes/js/jquery/ui/widget.min.js'&gt;&lt;/script&gt;\n&lt;script type='text/javascript' src='/wp-includes/js/jquery/ui/accordion.min.js'&gt;&lt;/script&gt;\n&lt;script type='text/javascript' src='/wp-content/themes/theme/js/theme.js'&gt;&lt;/script&gt;\n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/273986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm having a tough time including jquery-ui scripts and styles in my plugin. It seems that my `wp_enqueue_script` calls are simply ignored. There are already many questions similar to this one, but all answers I've found so far boil down to call `wp_enqueue_script` inside the `wp_enqueue_scripts` action hook, which I'm already doing. In the constructor of my class I call: ``` add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts') ); ``` and then, below: ``` public function enqueue_scripts() { wp_enqueue_script( 'jquery-ui-core', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-widget', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-mouse', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-accordion', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-autocomplete', false, array('jquery')); wp_enqueue_script( 'jquery-ui-slider', false, array('jquery')); ``` I've checked that the code actually gets executed each page load. However the pages lack the `<link>` tags for the jquery-ui library. I've already tried with and without the `jquery` dependency explicitly specified in the third argument of the `wp_enqueue_script` calls. I've also tried with a plain WP 4.8 installation with no plugins installed other than mine, and with the default twenty seventeen theme only. No dice. What's wrong with my code?
First of all, WordPress registers jQuery UI via [`wp_default_scripts()`](https://stackoverflow.com/questions/8849684/wordpress-jquery-ui-css-files). Dependencies are already set, so you only need to enqueue the script you really need (and not the core). Since you're not changing version number or anything, it is ok to only use the handle. ``` // no need to enqueue -core, because dependancies are set wp_enqueue_script( 'jquery-ui-widget' ); wp_enqueue_script( 'jquery-ui-mouse' ); wp_enqueue_script( 'jquery-ui-accordion' ); wp_enqueue_script( 'jquery-ui-autocomplete' ); wp_enqueue_script( 'jquery-ui-slider' ); ``` As for the stylesheets: **WordPress does not register jQuery UI styles by default!** In the comments, [butlerblog pointed out](https://wordpress.stackexchange.com/questions/273986/correct-way-to-enqueue-jquery-ui/273996#comment523572_273996) that according to the [Plugin Guidelines](https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/#8-plugins-may-not-send-executable-code-via-third-party-systems) > > Executing outside code within a plugin when not acting as a service is not allowed, for example: > > > * Calling third party CDNs for reasons other than font inclusions; all non-service related JavaScript and CSS must be included locally > > > This means loading the styles via CDN is not permitted and should always be done locally. You can do so by using `wp_enqueue_style()`.
274,016
<p>I would like to add content to the end of <a href="https://www.horizonhomes-samui.com/contact/" rel="nofollow noreferrer">this page</a> (below the form), immediately before the footer. Can I do this with a custom function, via a hook? Adding the content to the WordPress editor does not insert it at the bottom of the page as desired.</p> <p>I've tried two different custom functions, but they each placed the content in an undesired location (<a href="https://imgur.com/66runIU" rel="nofollow noreferrer">illustration</a>):</p> <p>-- I tried using the <code>wp_footer()</code> hook, but that placed the content at the end of my footer.</p> <p>-- I tried appending content using <code>the_content()</code> hook, with the code below, but that did not place the content where I wanted.</p> <pre><code>function yourprefix_add_to_content( $content ) { $content .= 'Your new content here'; return $content; } add_filter( 'the_content', 'yourprefix_add_to_content' ); </code></pre> <p>I <em>can</em> accomplish this by directly editing template, but I would rather not do that.</p>
[ { "answer_id": 274024, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>Unless that template that you don't want to edit has a <code>do_action()</code> function where you want to add the content, then no, you can't.</p>\n" }, { "answer_id": 274025, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>If your template uses the default comment form you can try to add with this <strong>hook</strong>: <code>comment_form_after</code>, he fires after the contact form renders. Or as de other answer says, only if your theme or the plugin you're using to add this form has an action to do this.</p>\n\n<p>See reference in the <a href=\"https://developer.wordpress.org/reference/hooks/comment_form_after/\" rel=\"nofollow noreferrer\">Codex</a>.</p>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I would like to add content to the end of [this page](https://www.horizonhomes-samui.com/contact/) (below the form), immediately before the footer. Can I do this with a custom function, via a hook? Adding the content to the WordPress editor does not insert it at the bottom of the page as desired. I've tried two different custom functions, but they each placed the content in an undesired location ([illustration](https://imgur.com/66runIU)): -- I tried using the `wp_footer()` hook, but that placed the content at the end of my footer. -- I tried appending content using `the_content()` hook, with the code below, but that did not place the content where I wanted. ``` function yourprefix_add_to_content( $content ) { $content .= 'Your new content here'; return $content; } add_filter( 'the_content', 'yourprefix_add_to_content' ); ``` I *can* accomplish this by directly editing template, but I would rather not do that.
Unless that template that you don't want to edit has a `do_action()` function where you want to add the content, then no, you can't.
274,017
<p>I'm a WordPress beginner and I'm working on a travel directory that user can register and have a front end control panel and have a front end submission form where user can add property description and of course images . </p> <p>I have a multi site installation but upload settings do not work for front end(max upload file size and file type). I suppose I can use a filter but I could not find something that works for front end... tried several plugins , all work in back end. </p> <p>Actually I need a step by step help or on line guide I could not find yet.</p> <p>Thanks!</p>
[ { "answer_id": 274019, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>You have some ways to do that:</p>\n\n<p>In your <strong>functions.php</strong> or <strong>wp-config.php</strong></p>\n\n<pre><code>@ini_set( 'upload_max_size' , '15M' );\n@ini_set( 'post_max_size', '15M');\n@ini_set( 'max_execution_time', '300' );\n</code></pre>\n\n<p>In your <strong>.htaccess</strong> (if you use apache2)</p>\n\n<pre><code>php_value upload_max_filesize 15M\nphp_value post_max_size 15M\nphp_value max_execution_time 300\nphp_value max_input_time 300\n</code></pre>\n\n<p>If you use <strong>nginx</strong></p>\n\n<pre><code>http {\n client_max_body_size 15m;\n}\n</code></pre>\n\n<p>In your <strong>php.ini</strong></p>\n\n<pre><code>upload_max_filesize = 15M\npost_max_size = 15M\nmax_execution_time = 300\n</code></pre>\n\n<p>They all work, so you can choose what best suits you, the size is set in MB so all the examples above will set the max upload to <strong>15MB</strong>.</p>\n" }, { "answer_id": 274088, "author": "webrex", "author_id": 123557, "author_profile": "https://wordpress.stackexchange.com/users/123557", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\nglobal $action;\nglobal $edit_id;\nglobal $embed_video_id;\nglobal $option_video;\nglobal $edit_link_details;\n$images='';\n$thumbid='';\n$attachid='';\n$arguments = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; 'attachment',\n 'post_parent' =&gt; $edit_id,\n 'post_status' =&gt; null,\n 'exclude' =&gt; get_post_thumbnail_id(),\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC'\n );\n $post_attachments = get_posts($arguments);\n $post_thumbnail_id = $thumbid = get_post_thumbnail_id( $edit_id );\n\n\nforeach ($post_attachments as $attachment) {\n $preview = wp_get_attachment_image_src($attachment-&gt;ID, 'wpestate_property_listings'); \n\n if($preview[0]!=''){\n $images .= '&lt;div class=\"uploaded_images\" data-imageid=\"'.$attachment-&gt;ID.'\"&gt;&lt;img src=\"'.$preview[0].'\" alt=\"thumb\" /&gt;&lt;i class=\"fa fa-trash-o\"&gt;&lt;/i&gt;';\n if($post_thumbnail_id == $attachment-&gt;ID){\n $images .='&lt;i class=\"fa thumber fa-star\"&gt;&lt;/i&gt;';\n }\n }else{\n $images .= '&lt;div class=\"uploaded_images\" data-imageid=\"'.$attachment-&gt;ID.'\"&gt;&lt;img src=\"'.get_template_directory_uri().'/img/pdf.png\" alt=\"thumb\" /&gt;&lt;i class=\"fa fa-trash-o\"&gt;&lt;/i&gt;';\n if($post_thumbnail_id == $attachment-&gt;ID){\n $images .='&lt;i class=\"fa thumber fa-star\"&gt;&lt;/i&gt;';\n }\n }\n\n\n $images .='&lt;/div&gt;';\n $attachid.= ','.$attachment-&gt;ID;\n }\n\n\n ?&gt;\n\n\n&lt;div class=\"col-md-12\" id=\"new_post2\"&gt;\n&lt;div class=\"user_dashboard_panel\"&gt;\n&lt;h4 class=\"user_dashboard_panel_title\"&gt;&lt;?php esc_html_e('Listing Media','wpestate');?&gt;&lt;/h4&gt;\n\n\n\n&lt;div class=\"col-md-12\" id=\"profile_message\"&gt;&lt;/div&gt;\n\n&lt;div class=\"col-md-12\"&gt;\n &lt;div id=\"upload-container\"&gt; \n &lt;div id=\"aaiu-upload-container\"&gt; \n &lt;div id=\"aaiu-upload-imagelist\"&gt;\n &lt;ul id=\"aaiu-ul-list\" class=\"aaiu-upload-list\"&gt;&lt;/ul&gt;\n &lt;/div&gt;\n\n &lt;div id=\"imagelist\"&gt;\n &lt;?php \n if($images!=''){\n print $images;\n }\n ?&gt; \n &lt;/div&gt;\n\n &lt;div id=\"aaiu-uploader\" class=\" wpb_btn-small wpestate_vc_button vc_button\"&gt;&lt;?php esc_html_e('Select Media','wpestate');?&gt;&lt;/div&gt;\n &lt;input type=\"hidden\" name=\"attachid\" id=\"attachid\" value=\"&lt;?php echo $attachid;?&gt;\"&gt;\n &lt;input type=\"hidden\" name=\"attachthumb\" id=\"attachthumb\" value=\"&lt;?php echo $thumbid;?&gt;\"&gt;\n &lt;p class=\"full_form full_form_image\"&gt;\n &lt;?php esc_html_e('*Double Click on the image to select featured. ','wpestate');?&gt;&lt;/br&gt;\n &lt;?php esc_html_e('**Change images order with Drag &amp; Drop. ','wpestate');?&gt;\n &lt;/p&gt;\n &lt;/div&gt; \n &lt;/div&gt;\n&lt;/div&gt;\n\n&lt;div class=\"col-md-4\"&gt;\n &lt;p&gt;\n &lt;label for=\"embed_video_type\"&gt;&lt;?php esc_html_e('Video from','wpestate');?&gt;&lt;/label&gt;\n &lt;select id=\"embed_video_type\" name=\"embed_video_type\" class=\"select-submit2\"&gt;\n &lt;?php print $option_video;?&gt;\n &lt;/select&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n\n\n&lt;div class=\"col-md-4\"&gt;\n &lt;p&gt; \n &lt;label for=\"embed_video_id\"&gt;&lt;?php esc_html_e('Video id: ','wpestate');?&gt;&lt;/label&gt;\n &lt;input type=\"text\" id=\"embed_video_id\" class=\"form-control\" name=\"embed_video_id\" size=\"40\" value=\"&lt;?php print $embed_video_id;?&gt;\"&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n\n &lt;div class=\"col-md-12\" style=\"display: inline-block;\"&gt; \n &lt;input type=\"hidden\" name=\"\" id=\"listing_edit\" value=\"&lt;?php echo $edit_id;?&gt;\"&gt;\n &lt;input type=\"submit\" class=\"wpb_btn-info wpb_btn-small wpestate_vc_button vc_button\" id=\"edit_prop_image\" value=\"&lt;?php esc_html_e('Save', 'wpestate') ?&gt;\" /&gt;\n &lt;a href=\"&lt;?php echo $edit_link_details;?&gt;\" class=\"next_submit_page\"&gt;&lt;?php esc_html_e('Go to Details settings (*make sure you click save first).','wpestate');?&gt;&lt;/a&gt;\n\n &lt;/div&gt;\n\n &lt;/div&gt; \n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123557/" ]
I'm a WordPress beginner and I'm working on a travel directory that user can register and have a front end control panel and have a front end submission form where user can add property description and of course images . I have a multi site installation but upload settings do not work for front end(max upload file size and file type). I suppose I can use a filter but I could not find something that works for front end... tried several plugins , all work in back end. Actually I need a step by step help or on line guide I could not find yet. Thanks!
You have some ways to do that: In your **functions.php** or **wp-config.php** ``` @ini_set( 'upload_max_size' , '15M' ); @ini_set( 'post_max_size', '15M'); @ini_set( 'max_execution_time', '300' ); ``` In your **.htaccess** (if you use apache2) ``` php_value upload_max_filesize 15M php_value post_max_size 15M php_value max_execution_time 300 php_value max_input_time 300 ``` If you use **nginx** ``` http { client_max_body_size 15m; } ``` In your **php.ini** ``` upload_max_filesize = 15M post_max_size = 15M max_execution_time = 300 ``` They all work, so you can choose what best suits you, the size is set in MB so all the examples above will set the max upload to **15MB**.
274,034
<p>I have setup a small website using LAMP (Raspbian) and Wordpress.<br> No domain name will be registered for the website.<br> For the moment I am accessing the site from inside the local network.<br> To access the site I just hit the IP address of the server (internal).<br> I want to access the site from outside the local network via the public IP.<br> The public IP is static and a Firewall is configured to translate the internal IP/default port(80) to the public static IP/(random port) and vice versa. Internal IP is static also and the RPi is directly connected to the FW via cable.</p> <p>If I send a request from an external IP the page never loads and inside my admin panel(via WP Statistics plugin) I can see the request.</p> <p>I would like to note that I have modified the <code>wp-config.php</code> and specifically these lines: </p> <pre><code>define('WP_HOME','http://internalIP/'); define('WP_SITEURL','http://internalIP/'); </code></pre> <p>What changes do I need to make so that the site will respond to the external requests? </p> <p>Is there anything I should check in my Wordpress/Apache/mySql/Linux configuration? </p> <p>Please let me know if any configuration info would be useful.</p>
[ { "answer_id": 274066, "author": "user42826", "author_id": 42826, "author_profile": "https://wordpress.stackexchange.com/users/42826", "pm_score": 2, "selected": true, "text": "<p>When installing WP onto an IP address (or hostname), WP will only respond to requests on that IP address. Any request from another IP address even if it resolves to the same server, will result in a redirect to a WP error page.</p>\n\n<p>In this situation, I would do this:</p>\n\n<ol>\n<li>Install WP on the public IP address. This will work if you can route to the public IP address internally. </li>\n<li>f you cannot route to the public IP address internally then I suggest installing on a hostname. You need to configure your DNS so that internally it will resolve to the internal IP address; and externally it will resolve to the public IP address.</li>\n</ol>\n" }, { "answer_id": 274595, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>While it isn’t quite considered to be <em>intended</em> mode of operation <code>WP_HOME</code> and <code>WP_SITEURL</code> <em>can</em> be declared dynamically conditional on <em>individual</em> request, rather than hardcoded.</p>\n\n<p>There is very little state in PHP natively, so if you tell it to handle specific request as if responding to this or that hostname/IP — it will.</p>\n\n<p>Of course while this will make WordPress core <em>boot</em>, there <em>is</em> some state on its side of things such as URLs captured in content and so on.</p>\n\n<p>In a nutshell this is certainly possible, but practicality of it depends a lot on specifics of the site.</p>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274034", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63180/" ]
I have setup a small website using LAMP (Raspbian) and Wordpress. No domain name will be registered for the website. For the moment I am accessing the site from inside the local network. To access the site I just hit the IP address of the server (internal). I want to access the site from outside the local network via the public IP. The public IP is static and a Firewall is configured to translate the internal IP/default port(80) to the public static IP/(random port) and vice versa. Internal IP is static also and the RPi is directly connected to the FW via cable. If I send a request from an external IP the page never loads and inside my admin panel(via WP Statistics plugin) I can see the request. I would like to note that I have modified the `wp-config.php` and specifically these lines: ``` define('WP_HOME','http://internalIP/'); define('WP_SITEURL','http://internalIP/'); ``` What changes do I need to make so that the site will respond to the external requests? Is there anything I should check in my Wordpress/Apache/mySql/Linux configuration? Please let me know if any configuration info would be useful.
When installing WP onto an IP address (or hostname), WP will only respond to requests on that IP address. Any request from another IP address even if it resolves to the same server, will result in a redirect to a WP error page. In this situation, I would do this: 1. Install WP on the public IP address. This will work if you can route to the public IP address internally. 2. f you cannot route to the public IP address internally then I suggest installing on a hostname. You need to configure your DNS so that internally it will resolve to the internal IP address; and externally it will resolve to the public IP address.
274,038
<p>I am using <em>pre_get_posts hook</em> in order to filter posts by custom terms. All working fine, but if i want to filter posts by 2 custom terms, the query only filters by the last term given. See my code below. I hook this into <em>pre_get_posts</em> but when both if statements are TRUE, only the last $query->set is done, meaning it won't filter the posts twice. Is there any way to accomplish this? Thanks</p> <pre><code>//For searching if( $query-&gt;is_main_query() &amp;&amp; isset( $_GET[ 'ls' ] ) ) { $rt_term_id = $_GET['listing_soort']; $rt_term_id_land = $_GET['listing_land']; // IF our soort vakantie is set and not empty - include it in the query if( isset( $rt_term_id ) &amp;&amp; ! empty( $rt_term_id ) ) { $query-&gt;set( 'tax_query', array( array( 'taxonomy' =&gt; 'vakantiesoorten_listing', 'field' =&gt; 'id', 'terms' =&gt; array($rt_term_id[0]), ) ) ); } // IF our land vakantie is set and not empty - include it in the query if( empty($_GET['location_geo_data']) &amp;&amp; isset( $rt_term_id_land ) &amp;&amp; ! empty( $rt_term_id_land ) ) { $query-&gt;set( 'tax_query', array( array( 'taxonomy' =&gt; 'landen_listing', 'field' =&gt; 'id', 'terms' =&gt; array($rt_term_id_land[0]), ) ) ); } } </code></pre>
[ { "answer_id": 274040, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You can do this, you just need to get the original value of the tax query, add the additional query, then set it again. The abbreviated version is:</p>\n\n<pre><code>// Get current tax query if it exists, otherwise get an empty array.\n$tax_query = $query-&gt;get( 'tax_query' ) ?: array();\n\nif ( true ) {\n $tax_query[] = array(); // Add first tax query.\n}\n\nif ( true ) {\n $tax_query[] = array(); // Add second tax query.\n}\n\n$query-&gt;set( 'tax_query', $tax_query ); // Set tax query parameter on query.\n</code></pre>\n" }, { "answer_id": 274041, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>Think of this pseudo code</p>\n\n<pre><code>if sky == blue\n set a = 5\nif grass == green\n set a = 7\n</code></pre>\n\n<p>What value will <code>a</code> have? Not 12.</p>\n\n<p>This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call <code>-&gt;set()</code> only once.</p>\n\n<pre><code>$tax_query = array();\nif( isset( $rt_term_id ) &amp;&amp; ! empty( $rt_term_id ) ) {\n $tax_query[] = array(\n 'taxonomy' =&gt; 'vakantiesoorten_listing',\n 'field' =&gt; 'id',\n 'terms' =&gt; array($rt_term_id[0]),\n );\n}\nif( empty($_GET['location_geo_data']) &amp;&amp; isset( $rt_term_id_land ) &amp;&amp; ! empty( $rt_term_id_land ) ) {\n $tax_query[] = array(\n 'taxonomy' =&gt; 'landen_listing',\n 'field' =&gt; 'id',\n 'terms' =&gt; array($rt_term_id_land[0]),\n );\n}\n$query-&gt;set( 'tax_query', $tax_query );\n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124244/" ]
I am using *pre\_get\_posts hook* in order to filter posts by custom terms. All working fine, but if i want to filter posts by 2 custom terms, the query only filters by the last term given. See my code below. I hook this into *pre\_get\_posts* but when both if statements are TRUE, only the last $query->set is done, meaning it won't filter the posts twice. Is there any way to accomplish this? Thanks ``` //For searching if( $query->is_main_query() && isset( $_GET[ 'ls' ] ) ) { $rt_term_id = $_GET['listing_soort']; $rt_term_id_land = $_GET['listing_land']; // IF our soort vakantie is set and not empty - include it in the query if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) { $query->set( 'tax_query', array( array( 'taxonomy' => 'vakantiesoorten_listing', 'field' => 'id', 'terms' => array($rt_term_id[0]), ) ) ); } // IF our land vakantie is set and not empty - include it in the query if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) { $query->set( 'tax_query', array( array( 'taxonomy' => 'landen_listing', 'field' => 'id', 'terms' => array($rt_term_id_land[0]), ) ) ); } } ```
Think of this pseudo code ``` if sky == blue set a = 5 if grass == green set a = 7 ``` What value will `a` have? Not 12. This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call `->set()` only once. ``` $tax_query = array(); if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) { $tax_query[] = array( 'taxonomy' => 'vakantiesoorten_listing', 'field' => 'id', 'terms' => array($rt_term_id[0]), ); } if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) { $tax_query[] = array( 'taxonomy' => 'landen_listing', 'field' => 'id', 'terms' => array($rt_term_id_land[0]), ); } $query->set( 'tax_query', $tax_query ); ```
274,039
<p>I have mt theme folder in my computer, where I did all the updates. Now I want to upload the new version of my theme with the changes I did. My question here: Do I just upload the theme folder via FTP and overwrite the existing one? Will this damage or change my posts or it will just update the theme design? I did this last night, but I'm afraid it changes everything...</p>
[ { "answer_id": 274040, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You can do this, you just need to get the original value of the tax query, add the additional query, then set it again. The abbreviated version is:</p>\n\n<pre><code>// Get current tax query if it exists, otherwise get an empty array.\n$tax_query = $query-&gt;get( 'tax_query' ) ?: array();\n\nif ( true ) {\n $tax_query[] = array(); // Add first tax query.\n}\n\nif ( true ) {\n $tax_query[] = array(); // Add second tax query.\n}\n\n$query-&gt;set( 'tax_query', $tax_query ); // Set tax query parameter on query.\n</code></pre>\n" }, { "answer_id": 274041, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>Think of this pseudo code</p>\n\n<pre><code>if sky == blue\n set a = 5\nif grass == green\n set a = 7\n</code></pre>\n\n<p>What value will <code>a</code> have? Not 12.</p>\n\n<p>This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call <code>-&gt;set()</code> only once.</p>\n\n<pre><code>$tax_query = array();\nif( isset( $rt_term_id ) &amp;&amp; ! empty( $rt_term_id ) ) {\n $tax_query[] = array(\n 'taxonomy' =&gt; 'vakantiesoorten_listing',\n 'field' =&gt; 'id',\n 'terms' =&gt; array($rt_term_id[0]),\n );\n}\nif( empty($_GET['location_geo_data']) &amp;&amp; isset( $rt_term_id_land ) &amp;&amp; ! empty( $rt_term_id_land ) ) {\n $tax_query[] = array(\n 'taxonomy' =&gt; 'landen_listing',\n 'field' =&gt; 'id',\n 'terms' =&gt; array($rt_term_id_land[0]),\n );\n}\n$query-&gt;set( 'tax_query', $tax_query );\n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114684/" ]
I have mt theme folder in my computer, where I did all the updates. Now I want to upload the new version of my theme with the changes I did. My question here: Do I just upload the theme folder via FTP and overwrite the existing one? Will this damage or change my posts or it will just update the theme design? I did this last night, but I'm afraid it changes everything...
Think of this pseudo code ``` if sky == blue set a = 5 if grass == green set a = 7 ``` What value will `a` have? Not 12. This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call `->set()` only once. ``` $tax_query = array(); if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) { $tax_query[] = array( 'taxonomy' => 'vakantiesoorten_listing', 'field' => 'id', 'terms' => array($rt_term_id[0]), ); } if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) { $tax_query[] = array( 'taxonomy' => 'landen_listing', 'field' => 'id', 'terms' => array($rt_term_id_land[0]), ); } $query->set( 'tax_query', $tax_query ); ```
274,042
<p>i want to display a div on every single page, but not on the frontpage. For that i used the following code in the functions.php</p> <pre><code> if (! is_front_page()) : '&lt;div class="button-kontakt"&gt; &lt;a href="/kontakt"&gt;&lt;p&gt;ANFRAGE&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;'; endif; </code></pre> <p>But my code is not working? The div is not shown. Somebody could help me with this?</p> <p>best regards</p> <p>Tom</p>
[ { "answer_id": 274045, "author": "James", "author_id": 122472, "author_profile": "https://wordpress.stackexchange.com/users/122472", "pm_score": 2, "selected": true, "text": "<p>You need to tell the PHP to echo the div. </p>\n\n<p><code>if (! is_front_page()) : \n echo '&lt;div class=\"button-kontakt\"&gt; &lt;a href=\"/kontakt\"&gt;&lt;p&gt;ANFRAGE&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;';\n endif;</code></p>\n\n<p>Unless you just want it on the top of the page, you need to add that code to a template file, not the functions file. If it is something that appears at the bottom of every page except the homepage, putting it in footer.php may be applicable. </p>\n\n<p>Also, have you set the page you don't want to see it on as the front page via the option in the Appearance->Customise menu?</p>\n" }, { "answer_id": 274046, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>Try this code:</p>\n\n<pre><code> if ( ! is_front_page() &amp;&amp; ! is_page( 'home' ) &amp;&amp; ! is_home() ) : \n echo '&lt;div class=\"button-kontakt\"&gt; &lt;a href=\"/kontakt\"&gt;&lt;p&gt;ANFRAGE&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;';\n endif; \n</code></pre>\n\n<p>or </p>\n\n<pre><code> if ( ! is_front_page() &amp;&amp; ! is_page( 'home' ) &amp;&amp; ! is_home() ) : ?&gt;\n &lt;div class=\"button-kontakt\"&gt; &lt;a href=\"/kontakt\"&gt;&lt;p&gt;ANFRAGE&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;\n\n&lt;?php endif; \n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
i want to display a div on every single page, but not on the frontpage. For that i used the following code in the functions.php ``` if (! is_front_page()) : '<div class="button-kontakt"> <a href="/kontakt"><p>ANFRAGE</p></a></div>'; endif; ``` But my code is not working? The div is not shown. Somebody could help me with this? best regards Tom
You need to tell the PHP to echo the div. `if (! is_front_page()) : echo '<div class="button-kontakt"> <a href="/kontakt"><p>ANFRAGE</p></a></div>'; endif;` Unless you just want it on the top of the page, you need to add that code to a template file, not the functions file. If it is something that appears at the bottom of every page except the homepage, putting it in footer.php may be applicable. Also, have you set the page you don't want to see it on as the front page via the option in the Appearance->Customise menu?
274,049
<p>I'm using gulp &amp; browserSync for server in WP development: </p> <pre><code>gulp.task('browser-sync', function () { browserSync.init({ proxy: projectURL }); }); </code></pre> <p>WordPress runs on <code>localhost:3000/mysite</code></p> <p>There is also a watch task that detects changes in php and reloads browser.</p> <p>For some reason though WP customizer doesn't load site in iframe with the following error: </p> <pre><code>Refused to display 'http://localhost:3000/mysite/2012/01/07/template-sticky/?customize_changese…10a90359901&amp;customize_theme=mysite&amp;customize_messenger_channel=preview-0' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors http://localhost". </code></pre> <p>It works fine <code>http://localhost/mysite</code> without the port though, but won't reload automatically. </p> <p>Is there a way to fix this somehow? </p>
[ { "answer_id": 290771, "author": "tpaksu", "author_id": 14452, "author_profile": "https://wordpress.stackexchange.com/users/14452", "pm_score": 1, "selected": false, "text": "<p>Maybe it may be late, but I recently have found a solution with a filter:</p>\n\n<pre><code>function theme_set_url_scheme($url, $path, $blog_id){\n if(isset($_GET[\"wp_port\"])){\n $parsed_url = parse_url($url);\n $parsed_url[\"port\"] = intval($_GET['wp_port']);\n $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';\n $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';\n $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';\n $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';\n $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';\n $pass = ($user || $pass) ? \"$pass@\" : '';\n $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';\n $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';\n $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';\n $url = \"$scheme$user$pass$host$port$path$query$fragment\";\n }\n return $url;\n}\nadd_filter(\"admin_url\", \"theme_set_url_scheme', null, 3);\n</code></pre>\n\n<p>And then open up the customizer with adding this querystring variable to the end:</p>\n\n<pre><code>&amp;wp_port=3000\n</code></pre>\n\n<p>I tried to do this without adding the querystring parameter, but I guess browsersync redirects the calls back to server port 80, so the 3000 custom port is only visible through browser and browsersync.</p>\n\n<hr>\n\n<p>Better option:</p>\n\n<p>Add the querystring parameter to browsersync setup like this:</p>\n\n<pre><code>options: {\n proxy: 'wordpress.dev?wp_port=3000',\n}\n</code></pre>\n\n<p>So you don't need to do anything manually. It works out of the box.</p>\n" }, { "answer_id": 295491, "author": "jamesc", "author_id": 137737, "author_profile": "https://wordpress.stackexchange.com/users/137737", "pm_score": 2, "selected": false, "text": "<p>Found a work around by adding ' localhost:3000' to the 'Content-Security-Policy' header:</p>\n\n<pre><code>function edit_customizer_headers () {\n function edit_csp_header ($headers) {\n $headers['Content-Security-Policy'] .= ' localhost:3000';\n return $headers;\n }\n add_filter('wp_headers', 'edit_csp_header');\n}\nadd_action('customize_preview_init', 'edit_customizer_headers');\n</code></pre>\n" }, { "answer_id": 301782, "author": "WraithKenny", "author_id": 279, "author_profile": "https://wordpress.stackexchange.com/users/279", "pm_score": 0, "selected": false, "text": "<p>Might be better to alter your gulp script in some variation of the tip on this bug report <a href=\"https://github.com/BrowserSync/browser-sync/issues/1241\" rel=\"nofollow noreferrer\">https://github.com/BrowserSync/browser-sync/issues/1241</a></p>\n\n<p>Hacking the source php files you are working on to get this working seems ... less good.</p>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I'm using gulp & browserSync for server in WP development: ``` gulp.task('browser-sync', function () { browserSync.init({ proxy: projectURL }); }); ``` WordPress runs on `localhost:3000/mysite` There is also a watch task that detects changes in php and reloads browser. For some reason though WP customizer doesn't load site in iframe with the following error: ``` Refused to display 'http://localhost:3000/mysite/2012/01/07/template-sticky/?customize_changese…10a90359901&customize_theme=mysite&customize_messenger_channel=preview-0' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors http://localhost". ``` It works fine `http://localhost/mysite` without the port though, but won't reload automatically. Is there a way to fix this somehow?
Found a work around by adding ' localhost:3000' to the 'Content-Security-Policy' header: ``` function edit_customizer_headers () { function edit_csp_header ($headers) { $headers['Content-Security-Policy'] .= ' localhost:3000'; return $headers; } add_filter('wp_headers', 'edit_csp_header'); } add_action('customize_preview_init', 'edit_customizer_headers'); ```
274,056
<p><a href="https://i.stack.imgur.com/a91zO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a91zO.jpg" alt="SearchResultsPage"></a></p> <p>I have designed and developed a responsive Wordpress site that is almost ready for launch for a client who is an actor and producer. I have been stuck on my requirements for the search results page for three days.</p> <p>My EXCERPT is far too long and includes repeated text from the Home page no matter what the search is for. Under the white links to the posts and pages for the search results, I want an excerpt of no more than 30 words which includes the search keyword (in this case the search keyword being “Ginsberg”) highlighted. So, a snippet of about 30 words, including the search term highlighted. That’s what I can’t get. When I have that, I have the search page I want. </p> <p>I have spent hours Googling and searching this on Stack Exchange and Stack Overflow, as well as attempts at finding the PHP logic required myself and failing. So if there is a solution to this already here, it’s well hidden!!</p> <p>WHAT I DO HAVE AND WHAT I’M HAPPY WITH IS: Say I do a search for the Beat Poet “Ginsberg” (screen shot attached). I get a main heading saying “2 results found for “Ginsberg”. Under that a smaller heading saying “Your ‘Ginsberg search results can be found at”” then below that I get a nicely styled list of two links to the two relevant pages. I want all that. That’s great. </p> <p>MY SEARCH FORM:</p> <pre><code>&lt;div class="search-cont"&gt; &lt;form class="searchinput" method="get" action="&lt;?php echo home_url(); ?&gt;" role="search"&gt; &lt;input type="search" class="searchinput" placeholder="&lt;?php echo esc_attr_x( 'Click icon or hit enter to search..', 'placeholder' ) ?&gt;" value="&lt;?php get_search_query() ?&gt;" name="s" title="&lt;?php echo esc_attr_x( 'Search for:', 'label' ) ?&gt;" /&gt; &lt;button type="submit" role="button" class="search-btn"/&gt;&lt;i class="fa fa-search" aria-hidden="true"&gt;&lt;/i&gt;&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- MY SEARCH PAGE:</p> <pre><code>&lt;div class="searchresultsbox"&gt; &lt;?php global $wp_query;?&gt; &lt;h2&gt; &lt;?php echo $wp_query-&gt;found_posts; ?&gt;&lt;?php _e( ' results found for', 'locale' ); ?&gt;: "&lt;?php the_search_query(); ?&gt;"&lt;/h2&gt; &lt;?php if ( have_posts() ) { ?&gt; &lt;h3&gt;&lt;?php printf( __( 'Your "%s" search results can be found at:', 'ptpisblogging' ), get_search_query() ); ?&gt;&lt;/h3&gt; &lt;?php while ( have_posts() ) { the_post(); ?&gt; &lt;h3&gt;&lt;a href="&lt;?php echo get_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt;&lt;/h3&gt; &lt;?php //echo substr(get_the_excerpt(), 0, 2); ?&gt; &lt;div class="h-readmore"&gt; &lt;a href="&lt;?php //the_permalink(); ?&gt;"&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php $args=array('s'=&gt;'test','order'=&gt; 'DESC', 'posts_per_page'=&gt;get_option('posts_per_page')); $query=new WP_Query($args); if( $query-&gt;have_posts()): while( $query-&gt;have_posts()): $query-&gt;the_post(); { echo $post-&gt;post_title; echo $post-&gt;post_content; } endwhile; else: endif; ?&gt; &lt;?php } ?&gt; &lt;?php paginate_links(); ?&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;param name="" value=""&gt; &lt;/div&gt;&lt;!-- /searchresultsbox --&gt; &lt;/div&gt;&lt;!-- /collcelltwo --&gt; &lt;/div&gt;&lt;!-- /tb-one-row --&gt; &lt;/div&gt;&lt;!-- /tb-one --&gt; </code></pre> <p>=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- IN 'functions.php'</p> <pre><code>add_action( 'pre_get_posts', function( $query ) { // Check that it is the query we want to change: front-end search query if( $query-&gt;is_main_query() &amp;&amp; ! is_admin() &amp;&amp; $query-&gt;is_search() ) { // Change the query parameters $query-&gt;set( 'posts_per_page', 4 ); } } ); </code></pre> <p>I am extremely grateful for your input. Thank you!! Keith</p>
[ { "answer_id": 274065, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Use str_replace to replace all occurances of the word to highlight with a around the word. Something like</p>\n\n<pre><code>// $searchresult = result of search process, \n//$highlightword = word you want to highlight\n$searchresult = str_replace( $highlightword, \n \"&lt;span style='background-color:#ffff00;'&gt;$highlightword&lt;/span&gt;\",\n $searchresult );\n</code></pre>\n\n<p>Adjust the background-color to what you want to use.</p>\n\n<p>To limit the number of words in the search result, see the answer to a similar question: <a href=\"https://stackoverflow.com/questions/965235/how-can-i-truncate-a-string-to-the-first-20-words-in-php\">https://stackoverflow.com/questions/965235/how-can-i-truncate-a-string-to-the-first-20-words-in-php</a> .</p>\n\n<p><em>Edited</em>: changed background color to yellow (#ffff00);</p>\n" }, { "answer_id": 340880, "author": "Gopala krishnan", "author_id": 168404, "author_profile": "https://wordpress.stackexchange.com/users/168404", "pm_score": 1, "selected": false, "text": "<p>This will helpful for you...\nUse this code at function.php </p>\n\n<pre><code>function wps_highlight_results($text){\n if(is_search()){\n $sr = get_query_var('s');\n $keys = explode(\" \",$sr);\n $text = preg_replace('/('.implode('|', $keys) .')/iu', '&lt;strong class=\"search-excerpt\"&gt;'.$sr.'&lt;/strong&gt;', $text);\n }\n return $text;\n}\nadd_filter('the_excerpt', 'wps_highlight_results');\n</code></pre>\n" }, { "answer_id": 399157, "author": "Alina", "author_id": 215787, "author_profile": "https://wordpress.stackexchange.com/users/215787", "pm_score": 0, "selected": false, "text": "<p>In search page, after this loop</p>\n<pre><code>&lt;?php if( have_posts() ) : while( have_posts() ) : the_post() ?&gt;\n</code></pre>\n<p>add this</p>\n<pre><code>&lt;?php \n$excerpt = get_the_excerpt(); \n$keys = explode(&quot; &quot;,$s); \n$excerpt = preg_replace(\n '/('.implode('|', $keys) .')/iu', \n '&lt;strong class=&quot;search-excerpt&quot;&gt;\\0&lt;/strong&gt;', \n $excerpt\n); \n?&gt;\n</code></pre>\n<p>Add at the place where you want to see Excerpt add this</p>\n<pre><code>&lt;?php echo $excerpt; ?&gt;\n</code></pre>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124257/" ]
[![SearchResultsPage](https://i.stack.imgur.com/a91zO.jpg)](https://i.stack.imgur.com/a91zO.jpg) I have designed and developed a responsive Wordpress site that is almost ready for launch for a client who is an actor and producer. I have been stuck on my requirements for the search results page for three days. My EXCERPT is far too long and includes repeated text from the Home page no matter what the search is for. Under the white links to the posts and pages for the search results, I want an excerpt of no more than 30 words which includes the search keyword (in this case the search keyword being “Ginsberg”) highlighted. So, a snippet of about 30 words, including the search term highlighted. That’s what I can’t get. When I have that, I have the search page I want. I have spent hours Googling and searching this on Stack Exchange and Stack Overflow, as well as attempts at finding the PHP logic required myself and failing. So if there is a solution to this already here, it’s well hidden!! WHAT I DO HAVE AND WHAT I’M HAPPY WITH IS: Say I do a search for the Beat Poet “Ginsberg” (screen shot attached). I get a main heading saying “2 results found for “Ginsberg”. Under that a smaller heading saying “Your ‘Ginsberg search results can be found at”” then below that I get a nicely styled list of two links to the two relevant pages. I want all that. That’s great. MY SEARCH FORM: ``` <div class="search-cont"> <form class="searchinput" method="get" action="<?php echo home_url(); ?>" role="search"> <input type="search" class="searchinput" placeholder="<?php echo esc_attr_x( 'Click icon or hit enter to search..', 'placeholder' ) ?>" value="<?php get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" /> <button type="submit" role="button" class="search-btn"/><i class="fa fa-search" aria-hidden="true"></i></button> </form> </div> ``` =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- MY SEARCH PAGE: ``` <div class="searchresultsbox"> <?php global $wp_query;?> <h2> <?php echo $wp_query->found_posts; ?><?php _e( ' results found for', 'locale' ); ?>: "<?php the_search_query(); ?>"</h2> <?php if ( have_posts() ) { ?> <h3><?php printf( __( 'Your "%s" search results can be found at:', 'ptpisblogging' ), get_search_query() ); ?></h3> <?php while ( have_posts() ) { the_post(); ?> <h3><a href="<?php echo get_permalink(); ?>"> <?php the_title(); ?> </a></h3> <?php //echo substr(get_the_excerpt(), 0, 2); ?> <div class="h-readmore"> <a href="<?php //the_permalink(); ?>"></a></div> <?php $args=array('s'=>'test','order'=> 'DESC', 'posts_per_page'=>get_option('posts_per_page')); $query=new WP_Query($args); if( $query->have_posts()): while( $query->have_posts()): $query->the_post(); { echo $post->post_title; echo $post->post_content; } endwhile; else: endif; ?> <?php } ?> <?php paginate_links(); ?> <?php } ?> </div> </div> </div> <param name="" value=""> </div><!-- /searchresultsbox --> </div><!-- /collcelltwo --> </div><!-- /tb-one-row --> </div><!-- /tb-one --> ``` =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- IN 'functions.php' ``` add_action( 'pre_get_posts', function( $query ) { // Check that it is the query we want to change: front-end search query if( $query->is_main_query() && ! is_admin() && $query->is_search() ) { // Change the query parameters $query->set( 'posts_per_page', 4 ); } } ); ``` I am extremely grateful for your input. Thank you!! Keith
This will helpful for you... Use this code at function.php ``` function wps_highlight_results($text){ if(is_search()){ $sr = get_query_var('s'); $keys = explode(" ",$sr); $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text); } return $text; } add_filter('the_excerpt', 'wps_highlight_results'); ```
274,097
<p>Right now my domain <code>www.example.com</code> is setup to force HTTPS and it works. The site also correctly links everything to HTTPS. (there are no occurences of HTTP in the database anywhere).</p> <p>But if you are visiting a subpage, you can change the url to HTTP again, for example <code>http://example.com/subpage/</code> and it will not enforce HTTPS.</p> <p>I have this rule in my <code>.htaccess</code> in the root:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L] </code></pre> <p>Any ideas what the cause of this is?</p>
[ { "answer_id": 274098, "author": "Junaid", "author_id": 66571, "author_profile": "https://wordpress.stackexchange.com/users/66571", "pm_score": 0, "selected": false, "text": "<p>Try this <code>htaccess</code> rule</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n" }, { "answer_id": 334326, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 3, "selected": true, "text": "<p>To globally redirect all your pages to HTTPS add the following lines to your <code>.htaccess</code>:</p>\n\n<pre><code># Globally force SSL.\nRewriteCond %{HTTPS} off\nRewriteCond %{HTTP:X-Forwarded-Proto} !https\nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>This should be placed directly after <code>RewriteEngine on</code> if you have no previous rewrites.</p>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124277/" ]
Right now my domain `www.example.com` is setup to force HTTPS and it works. The site also correctly links everything to HTTPS. (there are no occurences of HTTP in the database anywhere). But if you are visiting a subpage, you can change the url to HTTP again, for example `http://example.com/subpage/` and it will not enforce HTTPS. I have this rule in my `.htaccess` in the root: ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L] ``` Any ideas what the cause of this is?
To globally redirect all your pages to HTTPS add the following lines to your `.htaccess`: ``` # Globally force SSL. RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` This should be placed directly after `RewriteEngine on` if you have no previous rewrites.
274,103
<p>I'm wondering how I could change the menu in the twenty twelve theme to show the submenu items on click rather than hover?</p>
[ { "answer_id": 274106, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": -1, "selected": false, "text": "<p>You add a <code>:focus</code> pseudoclass to the same rule as <code>:hover</code>.</p>\n\n<pre><code>a:hover {\n color: red;\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>a:hover, \na:focus {\n color: red;\n}\n</code></pre>\n" }, { "answer_id": 274114, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>The basic answer is that you need to change the menu item element to have an <code>onclick()</code> function rather than an <code>onfocus()</code> . <code>Onfocus()</code> is what will happen when the mouse hovers over the element. <code>Onclick()</code> happens when you click the element.</p>\n\n<p>Where this is done depends on the theme code. You will need to dig into the theme code that creates the menu items and change the action for the menu element, which could also be inside a <code>&lt;form&gt;</code> tlement. </p>\n\n<p>And, use a Child Theme, so you don't lose your changes if the main theme gets an update.</p>\n" }, { "answer_id": 274117, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": true, "text": "<p>Menus can be slightly confusing since there's often JS and CSS interacting with different things.</p>\n\n<p>Looking at the twentytwelve theme, a quick method of achieving this would be to remove the CSS that is adding :hover display of the submenus.</p>\n\n<p>In <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/style.css#L1567\" rel=\"nofollow noreferrer\">style.css you would see .main-navigation ul li:hover > ul, on line 1,567</a>.</p>\n\n<p>In your child theme, you could just remove that selector and keep the other two selectors and all the properties in tact.</p>\n\n<p>That disables the :hover, but then you also need to make decisions on the behavior of the menu, submenus, and submenu submenus etc.</p>\n\n<p>Do you expect the submenus with submenus to behave the same way?</p>\n\n<p>Are you going to disable the top level menu item that is nested underneath?</p>\n\n<p>Are you going to create a toggle next to the menu item and keep the link clickable on the parent?</p>\n\n<p>Maybe a single click opens the submenu, and doubleclick takes the user to the URL?</p>\n\n<p>Paired with removing the CSS from above, you could have the parent menu item simply be a custom link going to '#' and the link text whatever you want the parent item to be.</p>\n\n<p>Twentytwelve already includes JS in the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/js/navigation.js#L41\" rel=\"nofollow noreferrer\">js/navigation.js file</a>, which is handling toggling a focus class on the element, so everything should work for you just removing that one line of CSS and changing your menu structure up.</p>\n\n<p>If this is for your own site or a controlled environment, then that might be all you need. If you don't want to change the menu structure, or want an alternative solution to handling that, you could easily use JS to prevent the links from being followed on click as well. This code would allow that to happen and you wouldn't have to mess around with your menu structure:</p>\n\n<pre><code> ( function( $ ) {\n $( '#menu-primary' ).find( '.menu-item-has-children &gt; a' ).on( 'click', function( e ) {\n e.preventDefault();\n });\n } )( jQuery );\n</code></pre>\n\n<p>If you're creating a new theme based on twentytwelve, then you should also give consideration to how others might intend to use the theme and prefer for their menus to work. You could create customizer controls to allow toggling the behavior of hover vs click and allowing parent menu items to be links etc.</p>\n\n<p>EDIT:</p>\n\n<p><strong>How would your JS affect users who don't use mice though?</strong></p>\n\n<p>The best way to tell is to try it out! :P</p>\n\n<ol>\n<li>Keyboard navigation:</li>\n</ol>\n\n<p>In testing this solution without a mouse by using my keyboard, I am able to successfully tab through the menus, submenus, and nested submenus easily. Pressing enter did not take me to the links of items that had children, but pressing enter on the final child allows the link to be opened. This seems like it works in the way that I would expect the navigation to work from a keyboard from the op's question. It probably wouldn't be harmful to rewrite the nav with aria labels to provide a better experience for users on screen readers, and allow better handling of the navigation with arrow keys if that's a concern for your site.</p>\n\n<ol start=\"2\">\n<li>Mobile or Touch Devices:</li>\n</ol>\n\n<p>The click event would be the last fired for a touch click simulation. The flow through events for touch would be:</p>\n\n<ul>\n<li>touchstart</li>\n<li>touchmove</li>\n<li>touchend</li>\n<li>mouseover</li>\n<li>mousemove</li>\n<li>mousedown</li>\n<li>mouseup</li>\n<li>click</li>\n</ul>\n\n<p>Twentytwelve is already <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/js/navigation.js#L44\" rel=\"nofollow noreferrer\">handling the mobile menus on the touchstart event in their navigation.js</a>, so calling preventDefault on click should still be fine to have it behave as well on mobile.</p>\n" } ]
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274103", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121004/" ]
I'm wondering how I could change the menu in the twenty twelve theme to show the submenu items on click rather than hover?
Menus can be slightly confusing since there's often JS and CSS interacting with different things. Looking at the twentytwelve theme, a quick method of achieving this would be to remove the CSS that is adding :hover display of the submenus. In [style.css you would see .main-navigation ul li:hover > ul, on line 1,567](https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/style.css#L1567). In your child theme, you could just remove that selector and keep the other two selectors and all the properties in tact. That disables the :hover, but then you also need to make decisions on the behavior of the menu, submenus, and submenu submenus etc. Do you expect the submenus with submenus to behave the same way? Are you going to disable the top level menu item that is nested underneath? Are you going to create a toggle next to the menu item and keep the link clickable on the parent? Maybe a single click opens the submenu, and doubleclick takes the user to the URL? Paired with removing the CSS from above, you could have the parent menu item simply be a custom link going to '#' and the link text whatever you want the parent item to be. Twentytwelve already includes JS in the [js/navigation.js file](https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/js/navigation.js#L41), which is handling toggling a focus class on the element, so everything should work for you just removing that one line of CSS and changing your menu structure up. If this is for your own site or a controlled environment, then that might be all you need. If you don't want to change the menu structure, or want an alternative solution to handling that, you could easily use JS to prevent the links from being followed on click as well. This code would allow that to happen and you wouldn't have to mess around with your menu structure: ``` ( function( $ ) { $( '#menu-primary' ).find( '.menu-item-has-children > a' ).on( 'click', function( e ) { e.preventDefault(); }); } )( jQuery ); ``` If you're creating a new theme based on twentytwelve, then you should also give consideration to how others might intend to use the theme and prefer for their menus to work. You could create customizer controls to allow toggling the behavior of hover vs click and allowing parent menu items to be links etc. EDIT: **How would your JS affect users who don't use mice though?** The best way to tell is to try it out! :P 1. Keyboard navigation: In testing this solution without a mouse by using my keyboard, I am able to successfully tab through the menus, submenus, and nested submenus easily. Pressing enter did not take me to the links of items that had children, but pressing enter on the final child allows the link to be opened. This seems like it works in the way that I would expect the navigation to work from a keyboard from the op's question. It probably wouldn't be harmful to rewrite the nav with aria labels to provide a better experience for users on screen readers, and allow better handling of the navigation with arrow keys if that's a concern for your site. 2. Mobile or Touch Devices: The click event would be the last fired for a touch click simulation. The flow through events for touch would be: * touchstart * touchmove * touchend * mouseover * mousemove * mousedown * mouseup * click Twentytwelve is already [handling the mobile menus on the touchstart event in their navigation.js](https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/js/navigation.js#L44), so calling preventDefault on click should still be fine to have it behave as well on mobile.
274,116
<p>Due to the setup of my template (and layout), I need to be able to place 4 different posts in 4 different divs.</p> <p>For example, my structure would be like this</p> <pre><code>&lt;div&gt;Post 1&lt;/div&gt; &lt;div&gt; &lt;div&gt;Post 2&lt;/div&gt; &lt;div&gt; &lt;div&gt;Post 3&lt;/div&gt; &lt;div&gt;Post 4&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But I'm having some trouble getting this to work, I use <code>get_posts</code> to get the 4 latest posts.</p> <pre><code>$posts = get_posts(array( 'post_type' =&gt; 'post', 'post_count' =&gt; 4 )); </code></pre> <p>And then I try to display my post</p> <pre><code>&lt;?php setup_postdata($posts[0]); ?&gt; &lt;?php get_template_part( 'template-parts/post-thumbnail' ); ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre> <p>In <code>template-parts/post-thumbnail.php</code> I'm trying to display the title and permalink, but it's always showing the title and link of the current page. Never of the actual post.</p>
[ { "answer_id": 274119, "author": "While1", "author_id": 111798, "author_profile": "https://wordpress.stackexchange.com/users/111798", "pm_score": 2, "selected": false, "text": "<p>Take it to your provinces</p>\n\n<pre><code>&lt;?php foreach ($posts as $post) : setup_postdata( $post ); ?&gt;\n &lt;div&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n&lt;?php endforeach; wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata</code></a> is important to reset a current query's result.</p>\n" }, { "answer_id": 274126, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 2, "selected": false, "text": "<p>$posts wouldn't be available within context of post-thumbnail.php if you're using <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part()</a>, so it will use the post ID found for the current page. You should use <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\">locate_template()</a> to make the variable available, which is what get_template_part uses internally, like this:</p>\n\n<pre><code>&lt;?php $posts = get_posts( array( 'post_type' =&gt; 'post', 'post_count' =&gt; 4 ) ); ?&gt;\n\n&lt;?php foreach ( $posts as $post ) : setup_postdata( $post ); ?&gt;\n &lt;?php locate_template( 'page-templates/post-thumbnail.php', true, false ); ?&gt;\n&lt;?php endforeach; wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>Then you would be able to have whatever you have in the page-templates/post-thumbnail.php template with the correct post data:</p>\n\n<pre><code>&lt;div&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 274131, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>Your problem is that the variable passed to <code>setup_postdata()</code> <em>must</em> be the global <code>$post</code> variable, like this:</p>\n\n<pre><code>// Reference global $post variable.\nglobal $post;\n\n// Get posts.\n$posts = get_posts(array(\n 'post_type' =&gt; 'post',\n 'post_count' =&gt; 4\n)); \n\n// Set global post variable to first post.\n$post = $posts[0];\n\n// Setup post data.\nsetup_postdata( $post );\n\n// Output template part.\nget_template_part( 'template-parts/post-thumbnail' );\n\n// Reset post data.\nwp_reset_postdata();\n</code></pre>\n\n<p>Now normal template functions, like <code>the_post_thumbnail()</code> inside the template part will reference the correct post.</p>\n" }, { "answer_id": 274132, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>Other than messing with the globals, you can write a custom loop that requires absolutely no extra work to make your template part work. For example:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 4\n);\n\n$my_query = new WP_Query($args);\nif ($my_query-&gt;have_posts()){\n while ($my_query-&gt;have_posts()){\n $my_query-&gt;the_post(); // This is where the post's data is set up\n get_template_part( 'template-parts/post-thumbnail' );\n }\n}\n</code></pre>\n\n<p>Done. You don't need to set up post's data for each post in the loop.</p>\n\n<p>By the way <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> itself uses a <code>WP_Query()</code> to fetch the posts, but the difference is that it doesn't set up the post's data for you, and it needs to be reset after the loop.</p>\n" } ]
2017/07/21
[ "https://wordpress.stackexchange.com/questions/274116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17561/" ]
Due to the setup of my template (and layout), I need to be able to place 4 different posts in 4 different divs. For example, my structure would be like this ``` <div>Post 1</div> <div> <div>Post 2</div> <div> <div>Post 3</div> <div>Post 4</div> </div> </div> ``` But I'm having some trouble getting this to work, I use `get_posts` to get the 4 latest posts. ``` $posts = get_posts(array( 'post_type' => 'post', 'post_count' => 4 )); ``` And then I try to display my post ``` <?php setup_postdata($posts[0]); ?> <?php get_template_part( 'template-parts/post-thumbnail' ); ?> <?php wp_reset_postdata(); ?> ``` In `template-parts/post-thumbnail.php` I'm trying to display the title and permalink, but it's always showing the title and link of the current page. Never of the actual post.
Your problem is that the variable passed to `setup_postdata()` *must* be the global `$post` variable, like this: ``` // Reference global $post variable. global $post; // Get posts. $posts = get_posts(array( 'post_type' => 'post', 'post_count' => 4 )); // Set global post variable to first post. $post = $posts[0]; // Setup post data. setup_postdata( $post ); // Output template part. get_template_part( 'template-parts/post-thumbnail' ); // Reset post data. wp_reset_postdata(); ``` Now normal template functions, like `the_post_thumbnail()` inside the template part will reference the correct post.
274,145
<p>I have a taxonomy page called <code>taxonomy-hotels.php</code> I need to get all posts related to particular <code>taxonomy-term</code>. Assume I have a term <code>5 star hotel</code> and it has 15 posts. But ony 10 returning/showing.</p> <p>Pleasa let me know how to get all posts ? Here is my current code.</p> <pre><code> &lt;?php if(have_posts()) : while(have_posts()) : the_post(); ?&gt; &lt;div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"&gt; &lt;div class="item"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; </code></pre>
[ { "answer_id": 274119, "author": "While1", "author_id": 111798, "author_profile": "https://wordpress.stackexchange.com/users/111798", "pm_score": 2, "selected": false, "text": "<p>Take it to your provinces</p>\n\n<pre><code>&lt;?php foreach ($posts as $post) : setup_postdata( $post ); ?&gt;\n &lt;div&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n&lt;?php endforeach; wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata</code></a> is important to reset a current query's result.</p>\n" }, { "answer_id": 274126, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 2, "selected": false, "text": "<p>$posts wouldn't be available within context of post-thumbnail.php if you're using <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part()</a>, so it will use the post ID found for the current page. You should use <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\">locate_template()</a> to make the variable available, which is what get_template_part uses internally, like this:</p>\n\n<pre><code>&lt;?php $posts = get_posts( array( 'post_type' =&gt; 'post', 'post_count' =&gt; 4 ) ); ?&gt;\n\n&lt;?php foreach ( $posts as $post ) : setup_postdata( $post ); ?&gt;\n &lt;?php locate_template( 'page-templates/post-thumbnail.php', true, false ); ?&gt;\n&lt;?php endforeach; wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>Then you would be able to have whatever you have in the page-templates/post-thumbnail.php template with the correct post data:</p>\n\n<pre><code>&lt;div&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 274131, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>Your problem is that the variable passed to <code>setup_postdata()</code> <em>must</em> be the global <code>$post</code> variable, like this:</p>\n\n<pre><code>// Reference global $post variable.\nglobal $post;\n\n// Get posts.\n$posts = get_posts(array(\n 'post_type' =&gt; 'post',\n 'post_count' =&gt; 4\n)); \n\n// Set global post variable to first post.\n$post = $posts[0];\n\n// Setup post data.\nsetup_postdata( $post );\n\n// Output template part.\nget_template_part( 'template-parts/post-thumbnail' );\n\n// Reset post data.\nwp_reset_postdata();\n</code></pre>\n\n<p>Now normal template functions, like <code>the_post_thumbnail()</code> inside the template part will reference the correct post.</p>\n" }, { "answer_id": 274132, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>Other than messing with the globals, you can write a custom loop that requires absolutely no extra work to make your template part work. For example:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 4\n);\n\n$my_query = new WP_Query($args);\nif ($my_query-&gt;have_posts()){\n while ($my_query-&gt;have_posts()){\n $my_query-&gt;the_post(); // This is where the post's data is set up\n get_template_part( 'template-parts/post-thumbnail' );\n }\n}\n</code></pre>\n\n<p>Done. You don't need to set up post's data for each post in the loop.</p>\n\n<p>By the way <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> itself uses a <code>WP_Query()</code> to fetch the posts, but the difference is that it doesn't set up the post's data for you, and it needs to be reset after the loop.</p>\n" } ]
2017/07/21
[ "https://wordpress.stackexchange.com/questions/274145", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85766/" ]
I have a taxonomy page called `taxonomy-hotels.php` I need to get all posts related to particular `taxonomy-term`. Assume I have a term `5 star hotel` and it has 15 posts. But ony 10 returning/showing. Pleasa let me know how to get all posts ? Here is my current code. ``` <?php if(have_posts()) : while(have_posts()) : the_post(); ?> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="item"> <a href="<?php the_permalink(); ?>"> <h2><?php the_title(); ?></h2> <?php the_post_thumbnail(); ?> </a> </div> </div> <?php endwhile; endif; ?> ```
Your problem is that the variable passed to `setup_postdata()` *must* be the global `$post` variable, like this: ``` // Reference global $post variable. global $post; // Get posts. $posts = get_posts(array( 'post_type' => 'post', 'post_count' => 4 )); // Set global post variable to first post. $post = $posts[0]; // Setup post data. setup_postdata( $post ); // Output template part. get_template_part( 'template-parts/post-thumbnail' ); // Reset post data. wp_reset_postdata(); ``` Now normal template functions, like `the_post_thumbnail()` inside the template part will reference the correct post.
274,206
<p>The following loop works great for me in getting posts with a given date with the use of the_time(...):</p> <pre><code>&lt;?php $myPost = new WP_Query( array( 'posts_per_page' =&gt; '50', 'orderby' =&gt; 'modified', 'order' =&gt; 'DESC' )); while ($myPost-&gt;have_posts()): $myPost-&gt;the_post(); ?&gt; &lt;div class="timeline-group"&gt; &lt;p class="modified-time"&gt;&lt;?php the_time('F j, Y') ?&gt;&lt;/p&gt; &lt;h5&gt;&lt;a href="&lt;?php the_permalink();?&gt;"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h5&gt; &lt;/div&gt; &lt;?php endwhile; //Reset Post Data wp_reset_postdata(); ?&gt; </code></pre> <p>But the first 10 posts always show the same date (i.e. July 21, 2017). I want to display that date only once for these 10 posts. And if I create a new post tomorrow, then it should then show a new date under these 10 posts, and then the post associating to that new date. How can I transform my loop to think that way without hard-coding dates?</p> <p>Thanks</p>
[ { "answer_id": 274211, "author": "dbeja", "author_id": 9585, "author_profile": "https://wordpress.stackexchange.com/users/9585", "pm_score": 1, "selected": false, "text": "<p>You can save the last date on a variable and on each iteration you compare the current date with the last date, and just write the date if they're different:</p>\n\n<pre><code>&lt;?php\n $myPost = new WP_Query( array(\n 'posts_per_page' =&gt; '50',\n 'orderby' =&gt; 'modified',\n 'order' =&gt; 'DESC'\n ));\n $lastDate = '';\n while ($myPost-&gt;have_posts()): $myPost-&gt;the_post();\n $currentDate = get_the_time('F j, Y');\n?&gt;\n\n&lt;?php if($currentDate != $lastDate): ?&gt;\n &lt;h2&gt;&lt;?php the_time('F j, Y') ?&gt;&lt;/h2&gt;\n &lt;?php $lastDate = $currentDate; ?&gt;\n&lt;?php endif; ?&gt;\n\n&lt;div class=\"timeline-group\"&gt;\n&lt;h5&gt;&lt;a href=\"&lt;?php the_permalink();?&gt;\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h5&gt;\n&lt;/div&gt;\n\n&lt;?php\n endwhile;\n //Reset Post Data\n wp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 274213, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Just use <code>the_date()</code>, it has this as a built-in feature.</p>\n\n<p>See the <a href=\"https://developer.wordpress.org/reference/functions/the_date/\" rel=\"nofollow noreferrer\">dev docs</a> for more info.</p>\n" } ]
2017/07/21
[ "https://wordpress.stackexchange.com/questions/274206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
The following loop works great for me in getting posts with a given date with the use of the\_time(...): ``` <?php $myPost = new WP_Query( array( 'posts_per_page' => '50', 'orderby' => 'modified', 'order' => 'DESC' )); while ($myPost->have_posts()): $myPost->the_post(); ?> <div class="timeline-group"> <p class="modified-time"><?php the_time('F j, Y') ?></p> <h5><a href="<?php the_permalink();?>"><?php the_title();?></a></h5> </div> <?php endwhile; //Reset Post Data wp_reset_postdata(); ?> ``` But the first 10 posts always show the same date (i.e. July 21, 2017). I want to display that date only once for these 10 posts. And if I create a new post tomorrow, then it should then show a new date under these 10 posts, and then the post associating to that new date. How can I transform my loop to think that way without hard-coding dates? Thanks
Just use `the_date()`, it has this as a built-in feature. See the [dev docs](https://developer.wordpress.org/reference/functions/the_date/) for more info.
274,259
<p>I am developing a wordpress page template exactly like <a href="https://blog.squarespace.com/blog/introducing-promotional-pop-ups" rel="nofollow noreferrer">this</a>. I have completed the design and have loaded the template once user goes to this page which using my template. I want to all posts in more article list open in this template without refreshing the page. but when i click on any post in the list it opens in a new page which is off course different from my page template. Please guide me how i can open the posts in the "more article" list open in my template. Here is my code i have till now.</p> <pre><code>&lt;?php if ( have_posts() ): while ( have_posts() ) : the_post(); ?&gt; &lt;div id="main" class="left-half" style=" background-image: url(&lt;?php echo intrigue_get_attachment(); ?&gt;); width:50%; display: inline-block; float: right; position: fixed; "&gt; &lt;h2 style="diplay:inline-block"&gt;&lt;a href="&lt;?php echo esc_url( home_url( '/' ) );?&gt;"&gt;&lt;?php bloginfo( 'name' );?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;input id="morearticlesbtn" class="button" type="button" onclick="openNav()" value="More Articles "&gt; &lt;div class="row"&gt; &lt;div class="post-meta col-md-6"&gt; &lt;p&gt;July 18, 2017&lt;/p&gt; By: &lt;a href="#"&gt;James Crock &lt;/a&gt; &lt;a href="#"&gt; Transport&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;div class="line"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="title-div"&gt; &lt;a href="&lt;?php echo the_permalink() ?&gt;"&gt; &lt;h1 class="title"&gt;&lt;?php the_title() ?&gt;&lt;/h1&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-9" &gt; &lt;div class="line bottom-line"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3 bottom-line-text"&gt; &lt;h4&gt;Next&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="right" class="right-half" style="width: 50%; display: inline-block; float:right;"&gt; &lt;div class=" content-div"&gt; &lt;?php the_content();?&gt; &lt;/div&gt; &lt;div class="tags content-div clear-fix"&gt; &lt;h6&gt;Tags:&lt;/h6&gt; &lt;?php echo get_the_tag_list();?&gt; &lt;!-- &lt;a href="#"&gt;&lt;h6&gt;Promotional&lt;/h6&gt;&lt;/a&gt;&lt;a href="#"&gt;&lt;h6&gt;Pop-Ups&lt;/h6&gt;&lt;/a&gt;--&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;!-- THE OFFCANVAS MENU --&gt; &lt;div id="mySidenav" class="sidenav menu"&gt; &lt;div class="hidden-menu-div"&gt; &lt;input class="button close-button" type="button" onclick="closeNav()" value="Hide List "&gt; &lt;div&gt; &lt;a href="#"&gt;About&lt;/a&gt; &lt;a href="#"&gt;Services&lt;/a&gt; &lt;a href="#"&gt;Clients&lt;/a&gt; &lt;a href="#"&gt;Contact&lt;/a&gt; &lt;a href="#search"&gt;Search&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); $wp_query-&gt;query('posts_per_page=6' . '&amp;paged='.$paged); while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); ?&gt; &lt;div class="col-sm-6 hiden-cat-post"&gt; &lt;a href="&lt;?php echo the_permalink(); ?&gt;" class="hidden-cat-item"&gt; &lt;div class="hidden-cat-thumbnail" &gt;&lt;?php the_post_thumbnail(array(340, 230))?&gt; &lt;/div&gt; &lt;div class="hidden-cat-item-text"&gt; &lt;h1 class="hidden-cat-item-title"&gt; &lt;?php the_title(); ?&gt; &lt;/h1&gt; &lt;div class="excerpt"&gt;&lt;/div&gt; &lt;div class="hidden-item-meta"&gt;jul 10,2017&lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php if ($paged &gt; 1) { ?&gt; &lt;nav id="nav-posts"&gt; &lt;div class="prev"&gt;&lt;?php next_posts_link('&amp;laquo; Previous Posts'); ?&gt;&lt;/div&gt; &lt;div class="next"&gt;&lt;?php previous_posts_link('Newer Posts &amp;raquo;'); ?&gt;&lt;/div&gt; &lt;/nav&gt; &lt;?php } else { ?&gt; &lt;nav id="nav-posts"&gt; &lt;div class="prev"&gt;&lt;?php next_posts_link('&amp;laquo; Previous Posts'); ?&gt;&lt;/div&gt; &lt;/nav&gt; &lt;?php } ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;!-- SCRIPT --&gt; &lt;script&gt; function openNav() { document.getElementById("mySidenav").style.width = "50%"; document.getElementById("main").style.marginLeft = "50%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("main").style.marginLeft= "0"; } </code></pre>
[ { "answer_id": 274284, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": -1, "selected": false, "text": "<p>You can simply put your code in single.php if you want all the posts to use this template style.</p>\n\n<p>Or if you want to restrict the use to a single post type, you can put the code in a file name single-{post-type}.php</p>\n\n<p>*replace {post-type} with your desired post type name.</p>\n" }, { "answer_id": 274414, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>What you are looking for is AJAX navigation. It's not that complicated, however it's not very easy too. I've written a simple example for you, I hope it helps you in your case.</p>\n<p>An AJAX request has 2 steps, first a front-end request that is sent out by browser when for example a user clicks a link or an element, then a response from the server.</p>\n<p>If we need to use that response in our website, there is a third step, which is, well... which is using the response in our website!</p>\n<h2>Creating an AJAX request on user's demand</h2>\n<p>If our user clicks a link, we have to stop the browser to navigating to that page. We can achieve this by using a jQuery function, called <code>preventDefault()</code>. This will prevent the default action of any element that is bound to it, whether it's a form, or a link.</p>\n<p>We need to build some custom link, to make sure we don't interfere with other links such as social networks. We'll add a class and an attribute to our navigation links to use it in the AJAX request.</p>\n<p>To get the next post's data, we use <code>get_next_post();</code> and <code>get_previous_post();</code>. We need the ID too. So:</p>\n<pre><code>$next_post = get_next_post();\n$prev_post = get_previous_post();\n// Check if the post exists\nif ( $prev_post ) { ?&gt;\n &lt;div class=&quot;prev ajax-link&quot; data-id=&quot;&lt;?php echo $prev_post-&gt;ID; ?&gt;&quot;&gt;&lt;?php _e('&amp;laquo; Previous Posts','text-domain'); ?&gt;&lt;/div&gt;&lt;?php\n}\nif ( $next_post ) { ?&gt;\n &lt;div class=&quot;next ajax-link&quot; data-id=&quot;&lt;?php echo $next_post-&gt;ID; ?&gt;&quot;&gt;&lt;?php _e('Newer Posts &amp;raquo;','text-domain'); ?&gt;&lt;/div&gt;&lt;?php\n}\n</code></pre>\n<p>Now, we'll write a jQuery function and disable the click event on our custom link:</p>\n<pre><code>(function($){\n $('.ajax-link').on('click',function(e){\n e.preventDefault();\n // The rest of the code goes here, check below\n });\n})(jQuery);\n</code></pre>\n<p>By using <code>$(this)</code> we get the ID of the post which we saved previously in the <code>data-id</code>:</p>\n<pre><code>var postId = $(this).attr('data-id');\n</code></pre>\n<p>Okay now we have the ID, let's create an AJAX request to out yet not written REST endpoint, and put the response in a DIV that is used as the container of our content:</p>\n<pre><code>$.get( 'http://example.com/prisma/ajax_navigation/', {\n ajaxid: postId\n}).done( function( response ) {\n if ( response.success ) {\n $( '#content-div' ).innerHTML( response.content );\n }\n});\n</code></pre>\n<p>Which <code>content-div</code> is the ID of the <code>DIV</code> that holds your content. It's the element's ID, not the class, and must be unique in the entire page. Alright, time to write the server side endpoint.</p>\n<h2>Creating a REST endpoint to return the post's data</h2>\n<p>Creating a REST endpoint is as easy as the next lines:</p>\n<pre><code>add_action( 'rest_api_init', function () {\n //Path to AJAX endpoint\n register_rest_route( 'prisma', '/ajax_navigation/', array(\n 'methods' =&gt; 'GET', \n 'callback' =&gt; 'ajax_navigation_function' \n ) );\n});\n</code></pre>\n<p>We've made an endpoint at <code>http://example.com/prisma/ajax_navigation/</code>. The path is accessible now, but we still need a callback function to return the post's data.</p>\n<pre><code>function ajax_navigation_function(){\n if( isset( $_REQUEST['ajaxid'] ) ){\n $post = get_post( $_REQUEST['ajaxid'] );\n $data['content'] = $post-&gt;post_content;\n $data['success'] = true;\n return $data;\n }\n}\n</code></pre>\n<p>That's it. Now whenever a user clicks the next post or previous post element, the content of the next or previous post will be fetched via AJAX, and inserted into the DIV element that has the ID of <code>content-div</code>.</p>\n<p>All done.</p>\n" } ]
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123788/" ]
I am developing a wordpress page template exactly like [this](https://blog.squarespace.com/blog/introducing-promotional-pop-ups). I have completed the design and have loaded the template once user goes to this page which using my template. I want to all posts in more article list open in this template without refreshing the page. but when i click on any post in the list it opens in a new page which is off course different from my page template. Please guide me how i can open the posts in the "more article" list open in my template. Here is my code i have till now. ``` <?php if ( have_posts() ): while ( have_posts() ) : the_post(); ?> <div id="main" class="left-half" style=" background-image: url(<?php echo intrigue_get_attachment(); ?>); width:50%; display: inline-block; float: right; position: fixed; "> <h2 style="diplay:inline-block"><a href="<?php echo esc_url( home_url( '/' ) );?>"><?php bloginfo( 'name' );?></a></h2> <input id="morearticlesbtn" class="button" type="button" onclick="openNav()" value="More Articles "> <div class="row"> <div class="post-meta col-md-6"> <p>July 18, 2017</p> By: <a href="#">James Crock </a> <a href="#"> Transport</a> </div> <div class="col-md-6"> <div class="line"></div> </div> </div> <div class="title-div"> <a href="<?php echo the_permalink() ?>"> <h1 class="title"><?php the_title() ?></h1></a> </div> <div class="row"> <div class="col-md-9" > <div class="line bottom-line"></div> </div> <div class="col-md-3 bottom-line-text"> <h4>Next</h4> </div> </div> </div> <div id="right" class="right-half" style="width: 50%; display: inline-block; float:right;"> <div class=" content-div"> <?php the_content();?> </div> <div class="tags content-div clear-fix"> <h6>Tags:</h6> <?php echo get_the_tag_list();?> <!-- <a href="#"><h6>Promotional</h6></a><a href="#"><h6>Pop-Ups</h6></a>--> </div> </div> <?php endwhile; endif; ?> <!-- THE OFFCANVAS MENU --> <div id="mySidenav" class="sidenav menu"> <div class="hidden-menu-div"> <input class="button close-button" type="button" onclick="closeNav()" value="Hide List "> <div> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> <a href="#search">Search</a> </div> </div> <?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); $wp_query->query('posts_per_page=6' . '&paged='.$paged); while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <div class="col-sm-6 hiden-cat-post"> <a href="<?php echo the_permalink(); ?>" class="hidden-cat-item"> <div class="hidden-cat-thumbnail" ><?php the_post_thumbnail(array(340, 230))?> </div> <div class="hidden-cat-item-text"> <h1 class="hidden-cat-item-title"> <?php the_title(); ?> </h1> <div class="excerpt"></div> <div class="hidden-item-meta">jul 10,2017</div> </div> </a> </div> <?php endwhile; ?> <?php if ($paged > 1) { ?> <nav id="nav-posts"> <div class="prev"><?php next_posts_link('&laquo; Previous Posts'); ?></div> <div class="next"><?php previous_posts_link('Newer Posts &raquo;'); ?></div> </nav> <?php } else { ?> <nav id="nav-posts"> <div class="prev"><?php next_posts_link('&laquo; Previous Posts'); ?></div> </nav> <?php } ?> <?php wp_reset_postdata(); ?> </div> <!-- SCRIPT --> <script> function openNav() { document.getElementById("mySidenav").style.width = "50%"; document.getElementById("main").style.marginLeft = "50%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("main").style.marginLeft= "0"; } ```
What you are looking for is AJAX navigation. It's not that complicated, however it's not very easy too. I've written a simple example for you, I hope it helps you in your case. An AJAX request has 2 steps, first a front-end request that is sent out by browser when for example a user clicks a link or an element, then a response from the server. If we need to use that response in our website, there is a third step, which is, well... which is using the response in our website! Creating an AJAX request on user's demand ----------------------------------------- If our user clicks a link, we have to stop the browser to navigating to that page. We can achieve this by using a jQuery function, called `preventDefault()`. This will prevent the default action of any element that is bound to it, whether it's a form, or a link. We need to build some custom link, to make sure we don't interfere with other links such as social networks. We'll add a class and an attribute to our navigation links to use it in the AJAX request. To get the next post's data, we use `get_next_post();` and `get_previous_post();`. We need the ID too. So: ``` $next_post = get_next_post(); $prev_post = get_previous_post(); // Check if the post exists if ( $prev_post ) { ?> <div class="prev ajax-link" data-id="<?php echo $prev_post->ID; ?>"><?php _e('&laquo; Previous Posts','text-domain'); ?></div><?php } if ( $next_post ) { ?> <div class="next ajax-link" data-id="<?php echo $next_post->ID; ?>"><?php _e('Newer Posts &raquo;','text-domain'); ?></div><?php } ``` Now, we'll write a jQuery function and disable the click event on our custom link: ``` (function($){ $('.ajax-link').on('click',function(e){ e.preventDefault(); // The rest of the code goes here, check below }); })(jQuery); ``` By using `$(this)` we get the ID of the post which we saved previously in the `data-id`: ``` var postId = $(this).attr('data-id'); ``` Okay now we have the ID, let's create an AJAX request to out yet not written REST endpoint, and put the response in a DIV that is used as the container of our content: ``` $.get( 'http://example.com/prisma/ajax_navigation/', { ajaxid: postId }).done( function( response ) { if ( response.success ) { $( '#content-div' ).innerHTML( response.content ); } }); ``` Which `content-div` is the ID of the `DIV` that holds your content. It's the element's ID, not the class, and must be unique in the entire page. Alright, time to write the server side endpoint. Creating a REST endpoint to return the post's data -------------------------------------------------- Creating a REST endpoint is as easy as the next lines: ``` add_action( 'rest_api_init', function () { //Path to AJAX endpoint register_rest_route( 'prisma', '/ajax_navigation/', array( 'methods' => 'GET', 'callback' => 'ajax_navigation_function' ) ); }); ``` We've made an endpoint at `http://example.com/prisma/ajax_navigation/`. The path is accessible now, but we still need a callback function to return the post's data. ``` function ajax_navigation_function(){ if( isset( $_REQUEST['ajaxid'] ) ){ $post = get_post( $_REQUEST['ajaxid'] ); $data['content'] = $post->post_content; $data['success'] = true; return $data; } } ``` That's it. Now whenever a user clicks the next post or previous post element, the content of the next or previous post will be fetched via AJAX, and inserted into the DIV element that has the ID of `content-div`. All done.
274,261
<p>I want my theme to have an 'about' page available by default when a user uses my theme.</p> <p>Is there a way to auto create a page when a user selects your template?</p> <p>Or some other way of achieving this?</p>
[ { "answer_id": 274269, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>The wp_insert_post() function is where to start <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_insert_post/</a> . You would place your code to create the post in the theme activation code. The googles show many examples of using that function.</p>\n\n<p>(Although I am not sure that theme users would want a post automatically created. Seems to me a bit of an imposition on your part. I sure wouldn't want an automatically created post on my site. Even with full disclosure prior to theme activation. Sort of like 'do no harm' to someone else's blog.)</p>\n" }, { "answer_id": 274286, "author": "Laura Smith", "author_id": 124398, "author_profile": "https://wordpress.stackexchange.com/users/124398", "pm_score": 1, "selected": false, "text": "<p>Starter content is a user friendly way of doing this, so it doesn't impose anything unwanted on the user. Take a look at <a href=\"https://make.wordpress.org/core/2016/11/30/starter-content-for-themes-in-4-7/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2016/11/30/starter-content-for-themes-in-4-7/</a></p>\n" }, { "answer_id": 274298, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>There is a hook specifically for this purpose, called <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow noreferrer\"><code>after_switch_theme</code></a>. You can hook into it and create your personal page after theme activation. Have a look at this:</p>\n\n<pre><code>add_action( 'after_switch_theme', 'create_page_on_theme_activation' );\n\nfunction create_page_on_theme_activation(){\n\n // Set the title, template, etc\n $new_page_title = __('About Us','text-domain'); // Page's title\n $new_page_content = ''; // Content goes here\n $new_page_template = 'page-custom-page.php'; // The template to use for the page\n $page_check = get_page_by_title($new_page_title); // Check if the page already exists\n // Store the above data in an array\n $new_page = array(\n 'post_type' =&gt; 'page', \n 'post_title' =&gt; $new_page_title,\n 'post_content' =&gt; $new_page_content,\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_name' =&gt; 'about-us'\n );\n // If the page doesn't already exist, create it\n if(!isset($page_check-&gt;ID)){\n $new_page_id = wp_insert_post($new_page);\n if(!empty($new_page_template)){\n update_post_meta($new_page_id, '_wp_page_template', $new_page_template);\n }\n }\n}\n</code></pre>\n\n<p>I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like <code>about-us</code> are very common, and might already exist but don't belong to your theme.</p>\n" }, { "answer_id": 317854, "author": "Sandip", "author_id": 152482, "author_profile": "https://wordpress.stackexchange.com/users/152482", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('wpmu_new_blog', 'create_pages');\nfunction create_pages(){\n$awesome_page_id = get_option(\"awesome_page_id\");\nif (!$awesome_page_id) {\n//create a new page and automatically assign the page template\n$post1 = array(\n'post_title' =&gt; \"Awesome Page!\",\n'post_content' =&gt; \"\",\n'post_status' =&gt; \"publish\",\n'post_type' =&gt; 'page',\n);\n$postID = wp_insert_post($post1, $error);\nupdate_post_meta($postID, \"_wp_page_template\", \"awesome-page.php\");\nupdate_option(\"awesome_page_id\", $postID);\n}\n}\n</code></pre>\n" } ]
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105958/" ]
I want my theme to have an 'about' page available by default when a user uses my theme. Is there a way to auto create a page when a user selects your template? Or some other way of achieving this?
There is a hook specifically for this purpose, called [`after_switch_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme). You can hook into it and create your personal page after theme activation. Have a look at this: ``` add_action( 'after_switch_theme', 'create_page_on_theme_activation' ); function create_page_on_theme_activation(){ // Set the title, template, etc $new_page_title = __('About Us','text-domain'); // Page's title $new_page_content = ''; // Content goes here $new_page_template = 'page-custom-page.php'; // The template to use for the page $page_check = get_page_by_title($new_page_title); // Check if the page already exists // Store the above data in an array $new_page = array( 'post_type' => 'page', 'post_title' => $new_page_title, 'post_content' => $new_page_content, 'post_status' => 'publish', 'post_author' => 1, 'post_name' => 'about-us' ); // If the page doesn't already exist, create it if(!isset($page_check->ID)){ $new_page_id = wp_insert_post($new_page); if(!empty($new_page_template)){ update_post_meta($new_page_id, '_wp_page_template', $new_page_template); } } } ``` I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like `about-us` are very common, and might already exist but don't belong to your theme.
274,277
<p>Someone made a website for me using wordpress.org. They said that they used "Wordpress Framework".</p> <p>Although I haven't changed anything, the logo of the website (which was an image near the top of the homepage is now missing. Not sure how it could disappear without me changing anything, but I am trying to rectify this myself. I am not familiar with wordpress and so am hoping I can find some assistance; at least an idea of where to begin.</p> <p>When I look what the active theme is, it just says 'Yescorts" which is the name of the website (yescorts.co.uk). I'm guessing that the creator customised an existing theme and then changed the name.</p> <p>I know I will probably get down-voted for being vague, but if I knew enough to be specific, I would be able to fix this already. I'm just looking for some suggestions of where I start looking to fix this. Or what more info I can provide to help you help me.</p> <p>Thanks in advance of any advice received. </p>
[ { "answer_id": 274269, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>The wp_insert_post() function is where to start <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_insert_post/</a> . You would place your code to create the post in the theme activation code. The googles show many examples of using that function.</p>\n\n<p>(Although I am not sure that theme users would want a post automatically created. Seems to me a bit of an imposition on your part. I sure wouldn't want an automatically created post on my site. Even with full disclosure prior to theme activation. Sort of like 'do no harm' to someone else's blog.)</p>\n" }, { "answer_id": 274286, "author": "Laura Smith", "author_id": 124398, "author_profile": "https://wordpress.stackexchange.com/users/124398", "pm_score": 1, "selected": false, "text": "<p>Starter content is a user friendly way of doing this, so it doesn't impose anything unwanted on the user. Take a look at <a href=\"https://make.wordpress.org/core/2016/11/30/starter-content-for-themes-in-4-7/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2016/11/30/starter-content-for-themes-in-4-7/</a></p>\n" }, { "answer_id": 274298, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>There is a hook specifically for this purpose, called <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow noreferrer\"><code>after_switch_theme</code></a>. You can hook into it and create your personal page after theme activation. Have a look at this:</p>\n\n<pre><code>add_action( 'after_switch_theme', 'create_page_on_theme_activation' );\n\nfunction create_page_on_theme_activation(){\n\n // Set the title, template, etc\n $new_page_title = __('About Us','text-domain'); // Page's title\n $new_page_content = ''; // Content goes here\n $new_page_template = 'page-custom-page.php'; // The template to use for the page\n $page_check = get_page_by_title($new_page_title); // Check if the page already exists\n // Store the above data in an array\n $new_page = array(\n 'post_type' =&gt; 'page', \n 'post_title' =&gt; $new_page_title,\n 'post_content' =&gt; $new_page_content,\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_name' =&gt; 'about-us'\n );\n // If the page doesn't already exist, create it\n if(!isset($page_check-&gt;ID)){\n $new_page_id = wp_insert_post($new_page);\n if(!empty($new_page_template)){\n update_post_meta($new_page_id, '_wp_page_template', $new_page_template);\n }\n }\n}\n</code></pre>\n\n<p>I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like <code>about-us</code> are very common, and might already exist but don't belong to your theme.</p>\n" }, { "answer_id": 317854, "author": "Sandip", "author_id": 152482, "author_profile": "https://wordpress.stackexchange.com/users/152482", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('wpmu_new_blog', 'create_pages');\nfunction create_pages(){\n$awesome_page_id = get_option(\"awesome_page_id\");\nif (!$awesome_page_id) {\n//create a new page and automatically assign the page template\n$post1 = array(\n'post_title' =&gt; \"Awesome Page!\",\n'post_content' =&gt; \"\",\n'post_status' =&gt; \"publish\",\n'post_type' =&gt; 'page',\n);\n$postID = wp_insert_post($post1, $error);\nupdate_post_meta($postID, \"_wp_page_template\", \"awesome-page.php\");\nupdate_option(\"awesome_page_id\", $postID);\n}\n}\n</code></pre>\n" } ]
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123873/" ]
Someone made a website for me using wordpress.org. They said that they used "Wordpress Framework". Although I haven't changed anything, the logo of the website (which was an image near the top of the homepage is now missing. Not sure how it could disappear without me changing anything, but I am trying to rectify this myself. I am not familiar with wordpress and so am hoping I can find some assistance; at least an idea of where to begin. When I look what the active theme is, it just says 'Yescorts" which is the name of the website (yescorts.co.uk). I'm guessing that the creator customised an existing theme and then changed the name. I know I will probably get down-voted for being vague, but if I knew enough to be specific, I would be able to fix this already. I'm just looking for some suggestions of where I start looking to fix this. Or what more info I can provide to help you help me. Thanks in advance of any advice received.
There is a hook specifically for this purpose, called [`after_switch_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme). You can hook into it and create your personal page after theme activation. Have a look at this: ``` add_action( 'after_switch_theme', 'create_page_on_theme_activation' ); function create_page_on_theme_activation(){ // Set the title, template, etc $new_page_title = __('About Us','text-domain'); // Page's title $new_page_content = ''; // Content goes here $new_page_template = 'page-custom-page.php'; // The template to use for the page $page_check = get_page_by_title($new_page_title); // Check if the page already exists // Store the above data in an array $new_page = array( 'post_type' => 'page', 'post_title' => $new_page_title, 'post_content' => $new_page_content, 'post_status' => 'publish', 'post_author' => 1, 'post_name' => 'about-us' ); // If the page doesn't already exist, create it if(!isset($page_check->ID)){ $new_page_id = wp_insert_post($new_page); if(!empty($new_page_template)){ update_post_meta($new_page_id, '_wp_page_template', $new_page_template); } } } ``` I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like `about-us` are very common, and might already exist but don't belong to your theme.
274,278
<p>I have a <code>page.php</code> in which I am defining a custom sub-menu to pass to <code>header.php</code>.</p> <p>I've tried using a constant (clumsy, I know): </p> <pre><code>define("CUSTOM_MENU", "&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;"); </code></pre> <p>right after this, the code is including the header:</p> <pre><code>get_header(); </code></pre> <p>In the header.php file, where the sub menu is, I am outputting either the custom sub-menu (if set), or a <code>wp_nav_menu</code>:</p> <pre><code>if (defined("CUSTOM_MENU")) echo constant("CUSTOM_MENU"); else wp_nav_menu(array(some stuff)); </code></pre> <p>bizarrely though, the <code>CUSTOM_MENU</code> constant becomes empty the moment <code>get_header()</code> gets called - and stays empty for the rest of <code>page.php</code>:</p> <pre><code> define("CUSTOM_MENU", "&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;"); echo constant("CUSTOM_MENU"); // The HTML code above get_header(); echo constant("CUSTOM_MENU"); // Null! </code></pre> <p>This happens for <em>any</em> method of storing the custom menu data that I use. I have tried:</p> <ul> <li>Different constant names</li> <li>Namespaced constants</li> <li>Global variables</li> <li>A function with a static variable</li> </ul> <p>I can't get my head around why this would happen! If <code>get_header()</code> somehow was including header.php using the http wrapper, then the value wouldn't be unset once we exit <code>get_header()</code> again.</p> <p>What is going on here? Am I overlooking something obvious?</p>
[ { "answer_id": 274322, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>There is most likely an issue of load order. The <code>get_header()</code> function does included your <code>header.php</code> file, so I'm not sure what's happening inside that template. One way to figure out is to include it using <code>include()</code> and check if the behavior is the same.</p>\n\n<p>I would suggest you hook into the <code>wp_head</code> or <code>init</code> and define your constant there. </p>\n\n<pre><code>add_action('init', 'define_my_constant' );\nfunction define_my_constant() {\n if ( ! defined( 'CUSTOM_MENU' ) &amp;&amp; is_page() ) {\n define('CUSTOM_MENU', '&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;');\n }\n}\n</code></pre>\n\n<p><code>init</code> is one of the earliest hooks that runs on WordPress, so your constant should be accessible in any theme or plugins at that point.</p>\n" }, { "answer_id": 274330, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>You could try to short-circut the <code>wp_nav_menu()</code> with this filter, for a given <code>theme_location</code>, on given pages:</p>\n\n<pre><code>/**\n * Filters whether to short-circuit the wp_nav_menu() output.\n *\n * Returning a non-null value to the filter will short-circuit\n * wp_nav_menu(), echoing that value if $args-&gt;echo is true,\n * returning that value otherwise.\n *\n * @since 3.9.0\n *\n * @see wp_nav_menu()\n *\n * @param string|null $output Nav menu output to short-circuit with. Default null.\n * @param stdClass $args An object containing wp_nav_menu() arguments.\n */\n$nav_menu = apply_filters( 'pre_wp_nav_menu', null, $args );\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<p>Here we override the navgational menu output, at the <code>primary</code> theme location, for the <code>test</code> page:</p>\n\n<pre><code>add_filter( 'pre_wp_nav_menu', function( $nav_menu, $args )\n{\n if ( 'primary' !== $args-&gt;theme_location )\n return $nav_menu;\n\n if( is_page( 'test' ) )\n $nav_menu = '&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;';\n\n return $nav_menu;\n}, 10, 2 );\n</code></pre>\n" } ]
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2161/" ]
I have a `page.php` in which I am defining a custom sub-menu to pass to `header.php`. I've tried using a constant (clumsy, I know): ``` define("CUSTOM_MENU", "<ul><li>Test</li></ul>"); ``` right after this, the code is including the header: ``` get_header(); ``` In the header.php file, where the sub menu is, I am outputting either the custom sub-menu (if set), or a `wp_nav_menu`: ``` if (defined("CUSTOM_MENU")) echo constant("CUSTOM_MENU"); else wp_nav_menu(array(some stuff)); ``` bizarrely though, the `CUSTOM_MENU` constant becomes empty the moment `get_header()` gets called - and stays empty for the rest of `page.php`: ``` define("CUSTOM_MENU", "<ul><li>Test</li></ul>"); echo constant("CUSTOM_MENU"); // The HTML code above get_header(); echo constant("CUSTOM_MENU"); // Null! ``` This happens for *any* method of storing the custom menu data that I use. I have tried: * Different constant names * Namespaced constants * Global variables * A function with a static variable I can't get my head around why this would happen! If `get_header()` somehow was including header.php using the http wrapper, then the value wouldn't be unset once we exit `get_header()` again. What is going on here? Am I overlooking something obvious?
There is most likely an issue of load order. The `get_header()` function does included your `header.php` file, so I'm not sure what's happening inside that template. One way to figure out is to include it using `include()` and check if the behavior is the same. I would suggest you hook into the `wp_head` or `init` and define your constant there. ``` add_action('init', 'define_my_constant' ); function define_my_constant() { if ( ! defined( 'CUSTOM_MENU' ) && is_page() ) { define('CUSTOM_MENU', '<ul><li>Test</li></ul>'); } } ``` `init` is one of the earliest hooks that runs on WordPress, so your constant should be accessible in any theme or plugins at that point.
274,294
<p>I have some code that returns the latest 5 images from the WordPress Media Library:</p> <pre><code>&lt;?php $excluded = array(1,35,37); $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; '5', 'category__not_in' =&gt; $excluded ); $images = get_posts($args); if (!empty($images)) { ?&gt; &lt;div class="wrap"&gt; &lt;h5&gt;&lt;span&gt;Recently&lt;/span&gt; Added&lt;/h5&gt; &lt;ul&gt; &lt;?php foreach ($images as $image) { $attachment_link = get_attachment_link( $image-&gt;ID ); echo "&lt;li&gt;&lt;a href='".$attachment_link."'&gt;".wp_get_attachment_image($image-&gt;ID)."&lt;/a&gt;&lt;/li&gt;"; } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I'm excluding some categories that I do not want to display (1,35,37). This works, but sometimes I have multiple categories assigned in addition to the excluded categories...if category 1 is selected and category 15 is selected the image will not show because category 1 is selected.</p> <p>What I am trying to do is exclude the categories only if those categories are selected by themselves. If they are selected with another category that isn't excluded they should show. So, an image that has category 1 and category 12 selected should still show because category 12 is not part of my excluded list.</p> <p>Can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 274322, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>There is most likely an issue of load order. The <code>get_header()</code> function does included your <code>header.php</code> file, so I'm not sure what's happening inside that template. One way to figure out is to include it using <code>include()</code> and check if the behavior is the same.</p>\n\n<p>I would suggest you hook into the <code>wp_head</code> or <code>init</code> and define your constant there. </p>\n\n<pre><code>add_action('init', 'define_my_constant' );\nfunction define_my_constant() {\n if ( ! defined( 'CUSTOM_MENU' ) &amp;&amp; is_page() ) {\n define('CUSTOM_MENU', '&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;');\n }\n}\n</code></pre>\n\n<p><code>init</code> is one of the earliest hooks that runs on WordPress, so your constant should be accessible in any theme or plugins at that point.</p>\n" }, { "answer_id": 274330, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>You could try to short-circut the <code>wp_nav_menu()</code> with this filter, for a given <code>theme_location</code>, on given pages:</p>\n\n<pre><code>/**\n * Filters whether to short-circuit the wp_nav_menu() output.\n *\n * Returning a non-null value to the filter will short-circuit\n * wp_nav_menu(), echoing that value if $args-&gt;echo is true,\n * returning that value otherwise.\n *\n * @since 3.9.0\n *\n * @see wp_nav_menu()\n *\n * @param string|null $output Nav menu output to short-circuit with. Default null.\n * @param stdClass $args An object containing wp_nav_menu() arguments.\n */\n$nav_menu = apply_filters( 'pre_wp_nav_menu', null, $args );\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<p>Here we override the navgational menu output, at the <code>primary</code> theme location, for the <code>test</code> page:</p>\n\n<pre><code>add_filter( 'pre_wp_nav_menu', function( $nav_menu, $args )\n{\n if ( 'primary' !== $args-&gt;theme_location )\n return $nav_menu;\n\n if( is_page( 'test' ) )\n $nav_menu = '&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;';\n\n return $nav_menu;\n}, 10, 2 );\n</code></pre>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274294", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I have some code that returns the latest 5 images from the WordPress Media Library: ``` <?php $excluded = array(1,35,37); $args = array( 'post_type' => 'attachment', 'numberposts' => '5', 'category__not_in' => $excluded ); $images = get_posts($args); if (!empty($images)) { ?> <div class="wrap"> <h5><span>Recently</span> Added</h5> <ul> <?php foreach ($images as $image) { $attachment_link = get_attachment_link( $image->ID ); echo "<li><a href='".$attachment_link."'>".wp_get_attachment_image($image->ID)."</a></li>"; } ?> </ul> </div> <?php } ?> ``` I'm excluding some categories that I do not want to display (1,35,37). This works, but sometimes I have multiple categories assigned in addition to the excluded categories...if category 1 is selected and category 15 is selected the image will not show because category 1 is selected. What I am trying to do is exclude the categories only if those categories are selected by themselves. If they are selected with another category that isn't excluded they should show. So, an image that has category 1 and category 12 selected should still show because category 12 is not part of my excluded list. Can anyone point me in the right direction? Thanks, Josh
There is most likely an issue of load order. The `get_header()` function does included your `header.php` file, so I'm not sure what's happening inside that template. One way to figure out is to include it using `include()` and check if the behavior is the same. I would suggest you hook into the `wp_head` or `init` and define your constant there. ``` add_action('init', 'define_my_constant' ); function define_my_constant() { if ( ! defined( 'CUSTOM_MENU' ) && is_page() ) { define('CUSTOM_MENU', '<ul><li>Test</li></ul>'); } } ``` `init` is one of the earliest hooks that runs on WordPress, so your constant should be accessible in any theme or plugins at that point.
274,295
<p>I try to change WordPress Twenty-sixteen them.</p> <p>I check the CSS carefully, can't finger out how could be the main menu display on the right of logo(and name of website).</p> <p>No float, no inline-block.</p> <p>I try to add float or display as block to menu and logo, doesn't work at all.How they do it?</p>
[ { "answer_id": 274301, "author": "Rajendra", "author_id": 107649, "author_profile": "https://wordpress.stackexchange.com/users/107649", "pm_score": -1, "selected": false, "text": "<p>In my suggestion, start a child theme of Twenty-sixteen theme,preferred way to Override parent theme functionalities and design.</p>\n" }, { "answer_id": 274310, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>The header of Twenty-Sixteen uses flexbox for alignment. You can set the flex direction of the site-header-main class to column to display the menu under the title/tagline/logo area:</p>\n\n<pre><code> .site-header-main {\n flex-direction: column;\n }\n</code></pre>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18787/" ]
I try to change WordPress Twenty-sixteen them. I check the CSS carefully, can't finger out how could be the main menu display on the right of logo(and name of website). No float, no inline-block. I try to add float or display as block to menu and logo, doesn't work at all.How they do it?
The header of Twenty-Sixteen uses flexbox for alignment. You can set the flex direction of the site-header-main class to column to display the menu under the title/tagline/logo area: ``` .site-header-main { flex-direction: column; } ```
274,296
<p>How can I make it so only members see post summaries on category pages? Currently only members can access them, but they still show up on category pages for non members. </p> <p>Note: I now made a plugin for this, you can get it at: <a href="https://github.com/NerdOfLinux/MemberOnly" rel="nofollow noreferrer">https://github.com/NerdOfLinux/MemberOnly</a></p>
[ { "answer_id": 274301, "author": "Rajendra", "author_id": 107649, "author_profile": "https://wordpress.stackexchange.com/users/107649", "pm_score": -1, "selected": false, "text": "<p>In my suggestion, start a child theme of Twenty-sixteen theme,preferred way to Override parent theme functionalities and design.</p>\n" }, { "answer_id": 274310, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>The header of Twenty-Sixteen uses flexbox for alignment. You can set the flex direction of the site-header-main class to column to display the menu under the title/tagline/logo area:</p>\n\n<pre><code> .site-header-main {\n flex-direction: column;\n }\n</code></pre>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
How can I make it so only members see post summaries on category pages? Currently only members can access them, but they still show up on category pages for non members. Note: I now made a plugin for this, you can get it at: <https://github.com/NerdOfLinux/MemberOnly>
The header of Twenty-Sixteen uses flexbox for alignment. You can set the flex direction of the site-header-main class to column to display the menu under the title/tagline/logo area: ``` .site-header-main { flex-direction: column; } ```
274,311
<pre><code>&lt;?php query_posts( array( 'showposts' =&gt; $number, 'nopaging' =&gt; 0, 'download_category' =&gt; $term-&gt;name, 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'post_views_count', 'order' =&gt; 'DESC', 'post_type' =&gt; array( 'download' ), 'post_status' =&gt; 'publish' ) ); while ( have_posts() ) : the_post(); ?&gt; </code></pre> <p>What this query does is sorting the page with the most views.</p> <p>Now what I want to do is make this into a clickable link, like: "Most Views". Then, when you click on Most views link, the page will sort based on the most views.</p> <p>Edit:</p> <p>I should indeed have provided more information regarding this question: We use a custom music template together with Easy Digital Downloads. <a href="http://www.dl-sounds.com" rel="nofollow noreferrer">http://www.dl-sounds.com</a></p> <p>As you can see there's a widget with "Most Popular". The code I provided comes from this widget. In the middle there's this box with "Newest Audio Files". In this box I want to add a link so it will be possible for visitors to sort the audio by most views.</p> <p>To be exact, I want to add a link in the sorting bar (Browse | Type | Tags) The sorting bar is a php file. </p> <p>I already did some testing with categories. I changed this query with the query above in the category php.</p> <pre><code>&lt;?php /* Genre Query */ query_posts( array( 'post_type' =&gt; 'download', 'posts_per_page' =&gt;'100000', 'download_category' =&gt; $term-&gt;name ) );while ( have_posts() ) : the_post(); ?&gt; </code></pre> <p>This is working fine. If I then browse the categories it is sorted by most views automatically. (on test site)</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n\n<p><code>$link = get_site_url() . '?most_views=' . (string) $param_value;</code></p>\n\n<p>Then in your function, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> and do something like this:</p>\n\n<pre><code>function query_most_views() {\n if ( $param_value = get_query_var( 'most_views', false ) ) {\n // Your query based optionally on your $param_value...\n }\n}\n</code></pre>\n" }, { "answer_id": 274316, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use <code>pre_get_posts</code> to modify the main query.</p>\n\n<pre><code>function sort_by_views($query) {\n if ( \n !is_admin() &amp;&amp; \n $query-&gt;is_main_query() &amp;&amp;\n $query-&gt;is_home() &amp;&amp;\n isset( $_REQUEST['sort_by_views'] ) \n ) {\n $query-&gt;set( 'post_type', 'download');\n $query-&gt;set( 'post_status', 'publish' );\n $query-&gt;set( 'posts_per_page', $number );\n $query-&gt;set( 'nopaging', false );\n $query-&gt;set( 'orderby', 'meta_value_num' );\n $query-&gt;set( 'meta_key', 'post_views_count' );\n $query-&gt;set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'sort_by_views' );\n</code></pre>\n\n<p>Now, if you navigate to <code>http://example.com/?sort_by_views=blabla</code>, your posts will be ordered by the views count.</p>\n\n<p>This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs.</p>\n\n<h2>One important note</h2>\n\n<p>Do not use <code>query_posts</code>. Use <code>WP_Query</code> instead. Using <code>query_posts</code> will alter the main query's data, which can mess with your content.</p>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274311", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124411/" ]
``` <?php query_posts( array( 'showposts' => $number, 'nopaging' => 0, 'download_category' => $term->name, 'orderby' => 'meta_value_num', 'meta_key' => 'post_views_count', 'order' => 'DESC', 'post_type' => array( 'download' ), 'post_status' => 'publish' ) ); while ( have_posts() ) : the_post(); ?> ``` What this query does is sorting the page with the most views. Now what I want to do is make this into a clickable link, like: "Most Views". Then, when you click on Most views link, the page will sort based on the most views. Edit: I should indeed have provided more information regarding this question: We use a custom music template together with Easy Digital Downloads. <http://www.dl-sounds.com> As you can see there's a widget with "Most Popular". The code I provided comes from this widget. In the middle there's this box with "Newest Audio Files". In this box I want to add a link so it will be possible for visitors to sort the audio by most views. To be exact, I want to add a link in the sorting bar (Browse | Type | Tags) The sorting bar is a php file. I already did some testing with categories. I changed this query with the query above in the category php. ``` <?php /* Genre Query */ query_posts( array( 'post_type' => 'download', 'posts_per_page' =>'100000', 'download_category' => $term->name ) );while ( have_posts() ) : the_post(); ?> ``` This is working fine. If I then browse the categories it is sorted by most views automatically. (on test site)
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,318
<p>Here are the arguments for my query.</p> <p>The query always shows the same order after every refresh.</p> <p>Explanation to the query: it show only 4 posts of the custom post type <code>projekte</code>. The post has a custom meta field called <code>ecpt_skills</code> and it should check if there is a string in it which is stored in the variable <code>$porjektart</code>. It also should not show the current post. And it should order the query by random. Everything works except the random.</p> <pre><code> $args = array( 'posts_per_page' =&gt; 4, 'post_type' =&gt; 'projekte', 'meta_key' =&gt; 'ecpt_skills', 'meta_value' =&gt; $projektart, 'meta_compare' =&gt; 'LIKE', post__not_in =&gt; array(get_the_ID()), 'orderby'=&gt; 'rand' ); </code></pre> <p>Does somebody know why this happens?</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n\n<p><code>$link = get_site_url() . '?most_views=' . (string) $param_value;</code></p>\n\n<p>Then in your function, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> and do something like this:</p>\n\n<pre><code>function query_most_views() {\n if ( $param_value = get_query_var( 'most_views', false ) ) {\n // Your query based optionally on your $param_value...\n }\n}\n</code></pre>\n" }, { "answer_id": 274316, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use <code>pre_get_posts</code> to modify the main query.</p>\n\n<pre><code>function sort_by_views($query) {\n if ( \n !is_admin() &amp;&amp; \n $query-&gt;is_main_query() &amp;&amp;\n $query-&gt;is_home() &amp;&amp;\n isset( $_REQUEST['sort_by_views'] ) \n ) {\n $query-&gt;set( 'post_type', 'download');\n $query-&gt;set( 'post_status', 'publish' );\n $query-&gt;set( 'posts_per_page', $number );\n $query-&gt;set( 'nopaging', false );\n $query-&gt;set( 'orderby', 'meta_value_num' );\n $query-&gt;set( 'meta_key', 'post_views_count' );\n $query-&gt;set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'sort_by_views' );\n</code></pre>\n\n<p>Now, if you navigate to <code>http://example.com/?sort_by_views=blabla</code>, your posts will be ordered by the views count.</p>\n\n<p>This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs.</p>\n\n<h2>One important note</h2>\n\n<p>Do not use <code>query_posts</code>. Use <code>WP_Query</code> instead. Using <code>query_posts</code> will alter the main query's data, which can mess with your content.</p>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124414/" ]
Here are the arguments for my query. The query always shows the same order after every refresh. Explanation to the query: it show only 4 posts of the custom post type `projekte`. The post has a custom meta field called `ecpt_skills` and it should check if there is a string in it which is stored in the variable `$porjektart`. It also should not show the current post. And it should order the query by random. Everything works except the random. ``` $args = array( 'posts_per_page' => 4, 'post_type' => 'projekte', 'meta_key' => 'ecpt_skills', 'meta_value' => $projektart, 'meta_compare' => 'LIKE', post__not_in => array(get_the_ID()), 'orderby'=> 'rand' ); ``` Does somebody know why this happens?
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,321
<p>I'm using the ACF plugin and overall it's working great. </p> <p>Expect for one small part:</p> <p>I've got a WYSIWYG text box on a page where I add a few enters, but when I look at the console I get an unexpected token &lt; error:</p> <pre><code>&lt;?php the_field('correctoutput'); ?&gt; </code></pre> <p>WHen I try to use the below part is just breaks:</p> <pre><code>&lt;?php echo the_field('correctoutput'); ?&gt; </code></pre> <p>When I use it also breaks:</p> <pre><code>&lt;?php echo json_encode the_field('correctoutput'); ?&gt; </code></pre> <p>This completely breaks the page:</p> <pre><code>&lt;?php get_field('correctoutput'); ?&gt; </code></pre> <p>It should add some text to a div when it's correct:</p> <pre><code> $('#correcto').innerHTML (&lt;?php the_field('correctoutput'); ?&gt;); </code></pre> <p>I've also used .text</p> <p>The only way it works is to catch it in a variable:</p> <pre><code>&lt;?php $correctoutput = get_post_meta( get_the_ID(), 'correctoutput', true ); ?&gt; </code></pre> <p>and then output it:</p> <pre><code>&lt;?php echo json_encode ($correctoutput); ?&gt; </code></pre> <p>But this will remove the <code>&lt;p&gt;&lt;/p&gt;</code> tags... and that's also what is giving the issue here.</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n\n<p><code>$link = get_site_url() . '?most_views=' . (string) $param_value;</code></p>\n\n<p>Then in your function, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> and do something like this:</p>\n\n<pre><code>function query_most_views() {\n if ( $param_value = get_query_var( 'most_views', false ) ) {\n // Your query based optionally on your $param_value...\n }\n}\n</code></pre>\n" }, { "answer_id": 274316, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use <code>pre_get_posts</code> to modify the main query.</p>\n\n<pre><code>function sort_by_views($query) {\n if ( \n !is_admin() &amp;&amp; \n $query-&gt;is_main_query() &amp;&amp;\n $query-&gt;is_home() &amp;&amp;\n isset( $_REQUEST['sort_by_views'] ) \n ) {\n $query-&gt;set( 'post_type', 'download');\n $query-&gt;set( 'post_status', 'publish' );\n $query-&gt;set( 'posts_per_page', $number );\n $query-&gt;set( 'nopaging', false );\n $query-&gt;set( 'orderby', 'meta_value_num' );\n $query-&gt;set( 'meta_key', 'post_views_count' );\n $query-&gt;set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'sort_by_views' );\n</code></pre>\n\n<p>Now, if you navigate to <code>http://example.com/?sort_by_views=blabla</code>, your posts will be ordered by the views count.</p>\n\n<p>This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs.</p>\n\n<h2>One important note</h2>\n\n<p>Do not use <code>query_posts</code>. Use <code>WP_Query</code> instead. Using <code>query_posts</code> will alter the main query's data, which can mess with your content.</p>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114176/" ]
I'm using the ACF plugin and overall it's working great. Expect for one small part: I've got a WYSIWYG text box on a page where I add a few enters, but when I look at the console I get an unexpected token < error: ``` <?php the_field('correctoutput'); ?> ``` WHen I try to use the below part is just breaks: ``` <?php echo the_field('correctoutput'); ?> ``` When I use it also breaks: ``` <?php echo json_encode the_field('correctoutput'); ?> ``` This completely breaks the page: ``` <?php get_field('correctoutput'); ?> ``` It should add some text to a div when it's correct: ``` $('#correcto').innerHTML (<?php the_field('correctoutput'); ?>); ``` I've also used .text The only way it works is to catch it in a variable: ``` <?php $correctoutput = get_post_meta( get_the_ID(), 'correctoutput', true ); ?> ``` and then output it: ``` <?php echo json_encode ($correctoutput); ?> ``` But this will remove the `<p></p>` tags... and that's also what is giving the issue here.
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,368
<p>I am trying to show the featured posts in my theme, with a custom field <code>mytheme_featured_post</code> which is 1 on the featured posts. </p> <p>However it does not seem to filter the posts down to only the posts in the meta query. </p> <pre><code>// WP_Query arguments. $featured = array( 'posts_per_page' =&gt; '5', 'meta_query' =&gt; array( array( 'key' =&gt; 'mytheme_featured_post', 'value' =&gt; '1', ), ), ); // The Query. $featured_query = new WP_Query( $featured ); if ( $featured_query -&gt; have_posts() ) { while ( $featured_query -&gt; have_posts() ) : $featured_query -&gt; the_post(); the_title(); endwhile; } </code></pre> <p><strong>Update:</strong> This args are working as intended: </p> <pre><code>// WP_Query arguments. $featured = array( 'posts_per_page' =&gt; '5', 'cat' =&gt; '1', 'meta_key' =&gt; 'mytheme_featured_post', 'meta_value' =&gt; '1', ); </code></pre>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n\n<p><code>$link = get_site_url() . '?most_views=' . (string) $param_value;</code></p>\n\n<p>Then in your function, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> and do something like this:</p>\n\n<pre><code>function query_most_views() {\n if ( $param_value = get_query_var( 'most_views', false ) ) {\n // Your query based optionally on your $param_value...\n }\n}\n</code></pre>\n" }, { "answer_id": 274316, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use <code>pre_get_posts</code> to modify the main query.</p>\n\n<pre><code>function sort_by_views($query) {\n if ( \n !is_admin() &amp;&amp; \n $query-&gt;is_main_query() &amp;&amp;\n $query-&gt;is_home() &amp;&amp;\n isset( $_REQUEST['sort_by_views'] ) \n ) {\n $query-&gt;set( 'post_type', 'download');\n $query-&gt;set( 'post_status', 'publish' );\n $query-&gt;set( 'posts_per_page', $number );\n $query-&gt;set( 'nopaging', false );\n $query-&gt;set( 'orderby', 'meta_value_num' );\n $query-&gt;set( 'meta_key', 'post_views_count' );\n $query-&gt;set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'sort_by_views' );\n</code></pre>\n\n<p>Now, if you navigate to <code>http://example.com/?sort_by_views=blabla</code>, your posts will be ordered by the views count.</p>\n\n<p>This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs.</p>\n\n<h2>One important note</h2>\n\n<p>Do not use <code>query_posts</code>. Use <code>WP_Query</code> instead. Using <code>query_posts</code> will alter the main query's data, which can mess with your content.</p>\n" } ]
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274368", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107055/" ]
I am trying to show the featured posts in my theme, with a custom field `mytheme_featured_post` which is 1 on the featured posts. However it does not seem to filter the posts down to only the posts in the meta query. ``` // WP_Query arguments. $featured = array( 'posts_per_page' => '5', 'meta_query' => array( array( 'key' => 'mytheme_featured_post', 'value' => '1', ), ), ); // The Query. $featured_query = new WP_Query( $featured ); if ( $featured_query -> have_posts() ) { while ( $featured_query -> have_posts() ) : $featured_query -> the_post(); the_title(); endwhile; } ``` **Update:** This args are working as intended: ``` // WP_Query arguments. $featured = array( 'posts_per_page' => '5', 'cat' => '1', 'meta_key' => 'mytheme_featured_post', 'meta_value' => '1', ); ```
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,382
<p>I just finished my blog I made locally and I would like to upload it to the server as it is in my computer, including the posts and the plugins. Is it possible to do it? </p> <p>I already have a WordPress installation in my server.</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n\n<p><code>$link = get_site_url() . '?most_views=' . (string) $param_value;</code></p>\n\n<p>Then in your function, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> and do something like this:</p>\n\n<pre><code>function query_most_views() {\n if ( $param_value = get_query_var( 'most_views', false ) ) {\n // Your query based optionally on your $param_value...\n }\n}\n</code></pre>\n" }, { "answer_id": 274316, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use <code>pre_get_posts</code> to modify the main query.</p>\n\n<pre><code>function sort_by_views($query) {\n if ( \n !is_admin() &amp;&amp; \n $query-&gt;is_main_query() &amp;&amp;\n $query-&gt;is_home() &amp;&amp;\n isset( $_REQUEST['sort_by_views'] ) \n ) {\n $query-&gt;set( 'post_type', 'download');\n $query-&gt;set( 'post_status', 'publish' );\n $query-&gt;set( 'posts_per_page', $number );\n $query-&gt;set( 'nopaging', false );\n $query-&gt;set( 'orderby', 'meta_value_num' );\n $query-&gt;set( 'meta_key', 'post_views_count' );\n $query-&gt;set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'sort_by_views' );\n</code></pre>\n\n<p>Now, if you navigate to <code>http://example.com/?sort_by_views=blabla</code>, your posts will be ordered by the views count.</p>\n\n<p>This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs.</p>\n\n<h2>One important note</h2>\n\n<p>Do not use <code>query_posts</code>. Use <code>WP_Query</code> instead. Using <code>query_posts</code> will alter the main query's data, which can mess with your content.</p>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114684/" ]
I just finished my blog I made locally and I would like to upload it to the server as it is in my computer, including the posts and the plugins. Is it possible to do it? I already have a WordPress installation in my server.
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,383
<p>I'm trying to put a line break in my input text field in customizer. I'm using a sanitization function like this</p> <pre><code>function sanitize_text( $input ) { $allowed_html = array( 'br' =&gt; array(), ); return wp_kses( $input, $allowed_html ); } </code></pre> <p>I also using php strip_tags but neither of them works.<br> Thanks in advance</p>
[ { "answer_id": 274386, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>I tried the code you shared above and everything appears to be working as intended.</p>\n\n<p>Are you sure you're creating and referencing the sanitize method correctly for the control?</p>\n\n<p>Here is the full code added to functions.php I used:</p>\n\n<pre><code> function test_sanitize_text( $input ) {\n $allowed_html = array(\n 'br' =&gt; array(),\n );\n\n return wp_kses( $input, $allowed_html );\n }\n\n function test_customizer( $wp_customize ) {\n $wp_customize-&gt;add_setting( 'themeslug_text_setting_id', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; 'Lorem Ipsum',\n 'sanitize_callback' =&gt; 'test_sanitize_text',\n ) );\n\n $wp_customize-&gt;add_control( 'themeslug_text_setting_id', array(\n 'type' =&gt; 'text',\n 'section' =&gt; 'title_tagline', // Add a default or your own section\n 'label' =&gt; __( 'Custom Text' ),\n 'description' =&gt; __( 'This is a custom text box.' ),\n ) );\n }\n</code></pre>\n\n<p>I went to the customizer to site identity section where the input was added and the following code and saved the customizer: <code>&lt;div class=\"htmls\"&gt;&lt;p&gt;testing&lt;/p&gt;&lt;br&gt;&lt;br&gt;&lt;p&gt;another&lt;/p&gt;&lt;/div&gt;</code></p>\n\n<p>Resulting value of <code>$mod = get_theme_mod( 'themeslug_text_setting_id' );</code>:</p>\n\n<p><code>string(22) \"testing&lt;br&gt;&lt;br&gt;another\"</code></p>\n" }, { "answer_id": 392918, "author": "Marcus Domingos", "author_id": 124054, "author_profile": "https://wordpress.stackexchange.com/users/124054", "pm_score": 1, "selected": false, "text": "<p>The only way I was able to make it work was that:</p>\n<p>functions.php</p>\n<pre><code>function test_customizer( $wp_customize ) {\n $wp_customize-&gt;add_setting( 'themeslug_text_setting_id', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; 'Lorem Ipsum',\n 'sanitize_callback' =&gt; 'sanitize_textarea_field',\n ) );\n\n $wp_customize-&gt;add_control( 'themeslug_text_setting_id', array(\n 'type' =&gt; 'text',\n 'section' =&gt; 'title_tagline', // Add a default or your own section\n 'label' =&gt; __( 'Custom Text' ),\n 'description' =&gt; __( 'This is a custom text box.' ),\n ) );\n}\n</code></pre>\n<p>Front (ex. index.php)</p>\n<pre><code>&lt;?php $themeslug_text_setting_id = get_theme_mod('themeslug_text_setting_id');\n if ($themeslug_text_setting_id) { \n echo nl2br( esc_html( $themeslug_text_setting_id ) );\n} ?&gt;\n</code></pre>\n<p>The <code>sanitize_textarea_field</code> is fundamental here.</p>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274383", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124443/" ]
I'm trying to put a line break in my input text field in customizer. I'm using a sanitization function like this ``` function sanitize_text( $input ) { $allowed_html = array( 'br' => array(), ); return wp_kses( $input, $allowed_html ); } ``` I also using php strip\_tags but neither of them works. Thanks in advance
The only way I was able to make it work was that: functions.php ``` function test_customizer( $wp_customize ) { $wp_customize->add_setting( 'themeslug_text_setting_id', array( 'capability' => 'edit_theme_options', 'default' => 'Lorem Ipsum', 'sanitize_callback' => 'sanitize_textarea_field', ) ); $wp_customize->add_control( 'themeslug_text_setting_id', array( 'type' => 'text', 'section' => 'title_tagline', // Add a default or your own section 'label' => __( 'Custom Text' ), 'description' => __( 'This is a custom text box.' ), ) ); } ``` Front (ex. index.php) ``` <?php $themeslug_text_setting_id = get_theme_mod('themeslug_text_setting_id'); if ($themeslug_text_setting_id) { echo nl2br( esc_html( $themeslug_text_setting_id ) ); } ?> ``` The `sanitize_textarea_field` is fundamental here.
274,408
<p><code>the_tags</code> by default is displaying as URL. I need to display it as plain text to insert inside HTML attribute.</p> <pre><code>&lt;?php $tag = the_tags(''); ?&gt; &lt;div class="image-portfolio" data-section="&lt;?php echo $tag ?&gt;"&gt; </code></pre>
[ { "answer_id": 274409, "author": "Viktor", "author_id": 81006, "author_profile": "https://wordpress.stackexchange.com/users/81006", "pm_score": 2, "selected": false, "text": "<p>Ok i figure it out</p>\n\n<pre><code>$tag = get_the_tags();\nforeach($tag as $tags) {\n echo $tags-&gt;name;\n}\n</code></pre>\n" }, { "answer_id": 274427, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": false, "text": "<p>I'm glad you figured it out, but below is a quick semantic alteration (swapping your use of <code>$tag</code> singular and <code>$tags</code> plural will help it read closer to what it is doing; functionally it is no different). </p>\n\n<p>I also added cases for inside and outside the Loop, and a conditional so you don't end up trying to foreach loop when there are no tags.</p>\n\n<h2>Commented:</h2>\n\n<pre><code>//We are inside the Loop here. Other wise we must pass an ID to get_the_tags()\n\n //returns array of objects\n $tags = get_the_tags();\n\n //make sure we have some\n if ($tags) {\n\n //foreach entry in array of tags, access the tag object\n foreach( $tags as $tag ) {\n\n //echo the name field from the tag object \n echo $tag-&gt;name;\n }\n }\n</code></pre>\n\n<h2>Inside Loop</h2>\n\n<pre><code> $tags = get_the_tags();\n\n if ($tags) {\n\n foreach( $tags as $tag ) {\n\n echo $tag-&gt;name;\n }\n }\n</code></pre>\n\n<h2>Outside Loop:</h2>\n\n<pre><code> $id = '10';\n\n $tags = get_the_tags( $id );\n\n if ($tags) {\n\n foreach( $tags as $tag ) {\n\n echo $tag-&gt;name;\n }\n }\n</code></pre>\n\n<hr>\n\n<h2>Further</h2>\n\n<p>Inside <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"noreferrer\">the loop</a>, <a href=\"https://developer.wordpress.org/reference/functions/get_the_tags/\" rel=\"noreferrer\"><code>get_the_tags()</code></a> uses the current post id. Outside of the loop, you need to pass it an id.\nEither way, it returns an <em>array</em> of <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"noreferrer\"><code>WP_TERM</code></a> <em>objects</em> for each term associated with the relevant post. </p>\n\n<pre><code>[0] =&gt; WP_Term Object\n (\n [term_id] =&gt; \n [name] =&gt; \n [slug] =&gt; \n [term_group] =&gt; \n [term_taxonomy_id] =&gt; \n [taxonomy] =&gt; post_tag\n [description] =&gt; \n [parent] =&gt; \n [count] =&gt; \n )\n</code></pre>\n\n<p>You could access each value the same way as above, i.e.:</p>\n\n<pre><code> $tags = get_the_tags(); \n if ($tags) {\n foreach( $tags as $tag ) {\n\n echo $tag-&gt;term_id;\n echo $tag-&gt;name;\n echo $tag-&gt;slug;\n echo $tag-&gt;term_group;\n echo $tag-&gt;term_taxonomy_id;\n echo $tag-&gt;taxonomy;\n echo $tag-&gt;description;\n echo $tag-&gt;parent;\n echo $tag-&gt;count;\n }\n }\n</code></pre>\n" }, { "answer_id": 274431, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>I love single lined codes, don't you?</p>\n\n<pre><code>&lt;?php echo implode(' ,' wp_get_post_tags( get_the_ID(), array('fields' =&gt; 'names') ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 331681, "author": "strikemike2k", "author_id": 163158, "author_profile": "https://wordpress.stackexchange.com/users/163158", "pm_score": 1, "selected": false, "text": "<p>This will display the tags as a comma-space separated string:</p>\n\n<pre><code>echo join(', ', array_map(function($t) { return $t-&gt;name; }, get_the_tags()));\n</code></pre>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81006/" ]
`the_tags` by default is displaying as URL. I need to display it as plain text to insert inside HTML attribute. ``` <?php $tag = the_tags(''); ?> <div class="image-portfolio" data-section="<?php echo $tag ?>"> ```
I'm glad you figured it out, but below is a quick semantic alteration (swapping your use of `$tag` singular and `$tags` plural will help it read closer to what it is doing; functionally it is no different). I also added cases for inside and outside the Loop, and a conditional so you don't end up trying to foreach loop when there are no tags. Commented: ---------- ``` //We are inside the Loop here. Other wise we must pass an ID to get_the_tags() //returns array of objects $tags = get_the_tags(); //make sure we have some if ($tags) { //foreach entry in array of tags, access the tag object foreach( $tags as $tag ) { //echo the name field from the tag object echo $tag->name; } } ``` Inside Loop ----------- ``` $tags = get_the_tags(); if ($tags) { foreach( $tags as $tag ) { echo $tag->name; } } ``` Outside Loop: ------------- ``` $id = '10'; $tags = get_the_tags( $id ); if ($tags) { foreach( $tags as $tag ) { echo $tag->name; } } ``` --- Further ------- Inside [the loop](https://codex.wordpress.org/The_Loop), [`get_the_tags()`](https://developer.wordpress.org/reference/functions/get_the_tags/) uses the current post id. Outside of the loop, you need to pass it an id. Either way, it returns an *array* of [`WP_TERM`](https://developer.wordpress.org/reference/classes/wp_term/) *objects* for each term associated with the relevant post. ``` [0] => WP_Term Object ( [term_id] => [name] => [slug] => [term_group] => [term_taxonomy_id] => [taxonomy] => post_tag [description] => [parent] => [count] => ) ``` You could access each value the same way as above, i.e.: ``` $tags = get_the_tags(); if ($tags) { foreach( $tags as $tag ) { echo $tag->term_id; echo $tag->name; echo $tag->slug; echo $tag->term_group; echo $tag->term_taxonomy_id; echo $tag->taxonomy; echo $tag->description; echo $tag->parent; echo $tag->count; } } ```
274,430
<p>I need to get posts belongs to few categories, but it should match following rule.</p> <p>let say I have category ids 100,105 &amp; 106. </p> <p>then I need <code>100 &amp;&amp; ( 105 || 106 )</code> this rule.</p> <p>I know following rules for separate <code>OR</code> &amp; <code>AND</code>, </p> <pre><code>$query = new WP_Query( array( 'cat' =&gt; '100,105,106' ) ); // 100 || 105 || 106 $query = new WP_Query( array( 'category__and' =&gt; array( 100,105,106 ) ) ); // 100 &amp;&amp; 105 &amp;&amp; 106 </code></pre> <p>But I need something like <code>100 &amp;&amp; ( 105 || 106 )</code>. How can I do that with <code>WP_Query</code> ?</p>
[ { "answer_id": 274435, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 1, "selected": false, "text": "<p>Not sure this is the best way, but I have managed to get the desired result set with following <code>$args</code> parameters. </p>\n\n<pre><code>$args['tax_query'] = array(\n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'id',\n 'terms' =&gt; array(100),\n ),\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'id',\n 'terms' =&gt; array(105,106),\n ),\n);\n</code></pre>\n" }, { "answer_id": 274458, "author": "Chris Pink", "author_id": 57686, "author_profile": "https://wordpress.stackexchange.com/users/57686", "pm_score": -1, "selected": false, "text": "<p>Set up your terms in php beforehand and then pass them to wp_query as a variable.</p>\n\n<pre><code>$mycats = array( ...\n some logic\n);\n</code></pre>\n\n<p>and then </p>\n\n<pre><code>$query = new WP_Query( array( 'cat' =&gt; $mycats ) );\n</code></pre>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274430", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
I need to get posts belongs to few categories, but it should match following rule. let say I have category ids 100,105 & 106. then I need `100 && ( 105 || 106 )` this rule. I know following rules for separate `OR` & `AND`, ``` $query = new WP_Query( array( 'cat' => '100,105,106' ) ); // 100 || 105 || 106 $query = new WP_Query( array( 'category__and' => array( 100,105,106 ) ) ); // 100 && 105 && 106 ``` But I need something like `100 && ( 105 || 106 )`. How can I do that with `WP_Query` ?
Not sure this is the best way, but I have managed to get the desired result set with following `$args` parameters. ``` $args['tax_query'] = array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array(100), ), array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array(105,106), ), ); ```
274,451
<p>I am very new to wordpress. I installed it on my linux server lately and uploaded a them on it. Everything looks good on my browser however if I try to access the website outside my network I am only getting the Text and not the CSS. I have read all different forum for the fix bt my problem still there. Here is my .htaccess</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I have changed the permission to 755 and 777 restarted apache but still same issue.</p>
[ { "answer_id": 274456, "author": "Chris Pink", "author_id": 57686, "author_profile": "https://wordpress.stackexchange.com/users/57686", "pm_score": 0, "selected": false, "text": "<p>Check you are addressing the CSS file correctly. How is it being called?</p>\n\n<p>The url should be along the lines of <code>ht|tp://yoursite.com/wordpress/wp-content/themes/yourtheme/style.css</code> you'll find somewhere that it's loading as <code>ht|tp://localhost/</code>and so it will load correctly on your machine but not on anyone else's.</p>\n\n<p>Have a look in Developer Tools for the URL of style.css</p>\n" }, { "answer_id": 313631, "author": "Alaksandar Jesus Gene", "author_id": 131473, "author_profile": "https://wordpress.stackexchange.com/users/131473", "pm_score": 0, "selected": false, "text": "<p>Have you tried with register script. Sample code</p>\n\n<pre><code> wp_register_script('jquery', get_template_directory_uri() . '/assets/all.js', false, null);\nwp_enqueue_script('jquery');\nwp_register_style('all', get_template_directory_uri() . '/assets/all.css', false, null);\nwp_enqueue_style('all');\n</code></pre>\n\n<p>If you have installed it in some folder, then your htaccess file should look like</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /yourfoldername/ -----&gt; This line\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /barter3/index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n\n<p>If you are getting the text, then .htaccess might not be the problem. </p>\n\n<p>Can u open the url in chrome browser, right click, inspect element, network \n-> Now refresh the page again\nYou will see styles tab in network\nClick on it, it will show the url you are hitting for the css. Confirm your url is correct.</p>\n" }, { "answer_id": 316696, "author": "Seiry", "author_id": 152336, "author_profile": "https://wordpress.stackexchange.com/users/152336", "pm_score": -1, "selected": false, "text": "<p>Go to \"General Settings\" and set \"wordpress address\" and \"site address\" from your localhost address to your domain address...</p>\n" }, { "answer_id": 342814, "author": "user2820204", "author_id": 171807, "author_profile": "https://wordpress.stackexchange.com/users/171807", "pm_score": 0, "selected": false, "text": "<p>You need to enter the full hostname and .local suffix into the WordPress Address and Site Address fields.</p>\n\n<p>eg. <a href=\"http://raspberrypi.local\" rel=\"nofollow noreferrer\">http://raspberrypi.local</a></p>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274451", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124482/" ]
I am very new to wordpress. I installed it on my linux server lately and uploaded a them on it. Everything looks good on my browser however if I try to access the website outside my network I am only getting the Text and not the CSS. I have read all different forum for the fix bt my problem still there. Here is my .htaccess ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` I have changed the permission to 755 and 777 restarted apache but still same issue.
Check you are addressing the CSS file correctly. How is it being called? The url should be along the lines of `ht|tp://yoursite.com/wordpress/wp-content/themes/yourtheme/style.css` you'll find somewhere that it's loading as `ht|tp://localhost/`and so it will load correctly on your machine but not on anyone else's. Have a look in Developer Tools for the URL of style.css
274,465
<p>I want to be able to create a shortcode that will return the post title when I pass in the ID of the post. I.E. [myshortcode_title ID=1234]</p> <p>I have a shortcode that pulls the post title from the current post: </p> <pre><code>function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' ); </code></pre> <p>I've seen shortcodes that can pass in attributes and return a result outside the loop, but I'm still new at WP shortcodes. </p>
[ { "answer_id": 274456, "author": "Chris Pink", "author_id": 57686, "author_profile": "https://wordpress.stackexchange.com/users/57686", "pm_score": 0, "selected": false, "text": "<p>Check you are addressing the CSS file correctly. How is it being called?</p>\n\n<p>The url should be along the lines of <code>ht|tp://yoursite.com/wordpress/wp-content/themes/yourtheme/style.css</code> you'll find somewhere that it's loading as <code>ht|tp://localhost/</code>and so it will load correctly on your machine but not on anyone else's.</p>\n\n<p>Have a look in Developer Tools for the URL of style.css</p>\n" }, { "answer_id": 313631, "author": "Alaksandar Jesus Gene", "author_id": 131473, "author_profile": "https://wordpress.stackexchange.com/users/131473", "pm_score": 0, "selected": false, "text": "<p>Have you tried with register script. Sample code</p>\n\n<pre><code> wp_register_script('jquery', get_template_directory_uri() . '/assets/all.js', false, null);\nwp_enqueue_script('jquery');\nwp_register_style('all', get_template_directory_uri() . '/assets/all.css', false, null);\nwp_enqueue_style('all');\n</code></pre>\n\n<p>If you have installed it in some folder, then your htaccess file should look like</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /yourfoldername/ -----&gt; This line\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /barter3/index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n\n<p>If you are getting the text, then .htaccess might not be the problem. </p>\n\n<p>Can u open the url in chrome browser, right click, inspect element, network \n-> Now refresh the page again\nYou will see styles tab in network\nClick on it, it will show the url you are hitting for the css. Confirm your url is correct.</p>\n" }, { "answer_id": 316696, "author": "Seiry", "author_id": 152336, "author_profile": "https://wordpress.stackexchange.com/users/152336", "pm_score": -1, "selected": false, "text": "<p>Go to \"General Settings\" and set \"wordpress address\" and \"site address\" from your localhost address to your domain address...</p>\n" }, { "answer_id": 342814, "author": "user2820204", "author_id": 171807, "author_profile": "https://wordpress.stackexchange.com/users/171807", "pm_score": 0, "selected": false, "text": "<p>You need to enter the full hostname and .local suffix into the WordPress Address and Site Address fields.</p>\n\n<p>eg. <a href=\"http://raspberrypi.local\" rel=\"nofollow noreferrer\">http://raspberrypi.local</a></p>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124490/" ]
I want to be able to create a shortcode that will return the post title when I pass in the ID of the post. I.E. [myshortcode\_title ID=1234] I have a shortcode that pulls the post title from the current post: ``` function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' ); ``` I've seen shortcodes that can pass in attributes and return a result outside the loop, but I'm still new at WP shortcodes.
Check you are addressing the CSS file correctly. How is it being called? The url should be along the lines of `ht|tp://yoursite.com/wordpress/wp-content/themes/yourtheme/style.css` you'll find somewhere that it's loading as `ht|tp://localhost/`and so it will load correctly on your machine but not on anyone else's. Have a look in Developer Tools for the URL of style.css
274,493
<p>How can you ensure a given plugin is run <em>last</em> before the page finishes rendering?</p> <p>Can it be ensured?</p> <p>Specifically, I am writing a plugin that I want to post-process all content of a given post/page (after any formatting, extra links, ad injections, etc). The rest of the blog doesn't need to be processed - just posts &amp; pages. </p>
[ { "answer_id": 274495, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 3, "selected": true, "text": "<p>You'll want to hook into \"the_content\" filter at a very high priority. Example:</p>\n\n<pre><code>function my_alter_the_content( $content ) {\n if ( in_array( get_post_type(), array( 'post', 'page' ) ) ) {\n // Do stuff here for posts and pages\n }\n return $content;\n}\nadd_action( 'the_content', 'my_alter_the_content', PHP_INT_MAX \n</code></pre>\n\n<p>);</p>\n\n<p>Using the PHP_INT_MAX constant for the hook priority you can ensure it runs as last as possible (most plugins/themes will just use the default priority of 10).</p>\n\n<p>The issue is when you say \"after all ad injections...etc\" that really depends how things are being added. Because if there are ads being added via javascript then of course the only way to override it would be via javascript.</p>\n" }, { "answer_id": 274503, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>Depending on what exactly you are trying to achieve, the <a href=\"https://developer.wordpress.org/reference/hooks/shutdown/\" rel=\"nofollow noreferrer\"><code>shutdown</code></a> action might be the place to hook into as it</p>\n\n<blockquote>\n <p>Fires just before PHP shuts down execution.</p>\n</blockquote>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5173/" ]
How can you ensure a given plugin is run *last* before the page finishes rendering? Can it be ensured? Specifically, I am writing a plugin that I want to post-process all content of a given post/page (after any formatting, extra links, ad injections, etc). The rest of the blog doesn't need to be processed - just posts & pages.
You'll want to hook into "the\_content" filter at a very high priority. Example: ``` function my_alter_the_content( $content ) { if ( in_array( get_post_type(), array( 'post', 'page' ) ) ) { // Do stuff here for posts and pages } return $content; } add_action( 'the_content', 'my_alter_the_content', PHP_INT_MAX ``` ); Using the PHP\_INT\_MAX constant for the hook priority you can ensure it runs as last as possible (most plugins/themes will just use the default priority of 10). The issue is when you say "after all ad injections...etc" that really depends how things are being added. Because if there are ads being added via javascript then of course the only way to override it would be via javascript.
274,496
<p>I'm using the following to add specific classes to my odd/even posts but I also need to add a class to all posts except the first one. Is there a quick, semantic way to do this minus the first post?</p> <pre><code>&lt;?php $homenews_query = new WP_Query( 'posts_per_page=4' ); ?&gt; &lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt; &lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt; &lt;!-- stuff here --&gt; &lt;?php else: ?&gt; &lt;!-- stuff here --&gt; &lt;?php endif ?&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; </code></pre> <p>I've tried various ways to do this--mostly with jQuery (addClass and removeClass) and it's not been working for me. </p> <p>TIA!</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:</p>\n\n<pre><code>&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>then in your <strong>css</strong>:</p>\n\n<pre><code>.post:not(:first-child) {\n // add the rules of the class you wanted to add\n}\n</code></pre>\n\n<p>Just select all elements except the first-child of posts with the class <code>post</code> and add the rules of the class you wanted to add.</p>\n\n<p>You also can do with <strong>js/jquery</strong>:</p>\n\n<pre><code>$('.post:not(:first-child)').addClass('myclass');\n</code></pre>\n\n<p>It's the same logic as with css, but if you wnat to add a separate class you can do it.</p>\n\n<p>or you can do with <strong>php</strong>:</p>\n\n<pre><code>&lt;?php $count = 0 ?&gt;\n&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($count != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n\n&lt;?php \n $count++;\n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>I know that the first post, is the one in the <code>index 0</code> so a just check if the count is != 0.</p>\n\n<p>or simpler, you have an attribute called <code>current_post</code> just check if you're not in the first post, like this:</p>\n\n<pre><code>&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n&lt;?php \n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p><strong>Edit: I posted with the inverse logic, fixed now.</strong></p>\n" }, { "answer_id": 274499, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>The easiest thing is to add a counter variable to your loop. But also be sure to add a posts exists check to prevent issues if no posts are found and I highly recommend using good commenting and syntax - it's a good habit ;)</p>\n\n<p>Here is an example of the modified code:</p>\n\n<pre><code>&lt;?php\n// Query posts\n$homenews_query = new WP_Query( 'posts_per_page=4' );\n\n// If posts are found do stuff\nif ( $the_query-&gt;have_posts() ) :\n\n // Define counter\n $count = 0;\n\n // Loop through posts\n while ( $homenews_query-&gt;have_posts() ) : $homenews_query-&gt;the_post();\n\n // Add to counter for each entry\n $count ++;\n\n // Define default classname for entry\n $class = 'entry';\n\n // Add class name to all excerpt the first\n if ( 1 !== $count ) {\n $class .= ' first-post';\n }\n\n // Add odd/even classes\n $class .= $count % 2 == 0 ? ' even' : ' odd';\n\n\n // No posts found\n else: ?&gt;\n\n &lt;!-- stuff here --&gt;\n\n &lt;?php endif ?&gt;\n\n &lt;?php\n // End loop\n endwhile;\n\n // Reset post data to prevent query conflicts\n wp_reset_postdata(); \n\n// End posts check\nendif; ?&gt;\n</code></pre>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7662/" ]
I'm using the following to add specific classes to my odd/even posts but I also need to add a class to all posts except the first one. Is there a quick, semantic way to do this minus the first post? ``` <?php $homenews_query = new WP_Query( 'posts_per_page=4' ); ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` I've tried various ways to do this--mostly with jQuery (addClass and removeClass) and it's not been working for me. TIA!
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,515
<p>I have a simple columns shortcode. (How) can this be adjusted to output a containing div around multiple columns? </p> <p>Really don't want to nest shortcodes in the frontend. Perhaps some kind of filter?</p> <p>My <code>functions.php</code> looks like this:</p> <pre><code>// Columns shortcode function abc_custom_column( $atts, $content = null ) { return '&lt;div class="column"&gt;' . do_shortcode( $content ) . '&lt;/div&gt;'; } add_shortcode('col', 'abc_custom_column'); </code></pre> <p>Hoping for something like: </p> <pre><code>if ( 'col' === &gt;2 ) { return '&lt;div class="multi_columns"&gt;' . do_shortcode( $content ) . '&lt;/div&gt;'; } else { return '&lt;div class="column"&gt;' . do_shortcode( $content ) . '&lt;/div&gt;'; } </code></pre> <p>*** I know that clearly won't work / isn't valid code.</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:</p>\n\n<pre><code>&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>then in your <strong>css</strong>:</p>\n\n<pre><code>.post:not(:first-child) {\n // add the rules of the class you wanted to add\n}\n</code></pre>\n\n<p>Just select all elements except the first-child of posts with the class <code>post</code> and add the rules of the class you wanted to add.</p>\n\n<p>You also can do with <strong>js/jquery</strong>:</p>\n\n<pre><code>$('.post:not(:first-child)').addClass('myclass');\n</code></pre>\n\n<p>It's the same logic as with css, but if you wnat to add a separate class you can do it.</p>\n\n<p>or you can do with <strong>php</strong>:</p>\n\n<pre><code>&lt;?php $count = 0 ?&gt;\n&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($count != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n\n&lt;?php \n $count++;\n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>I know that the first post, is the one in the <code>index 0</code> so a just check if the count is != 0.</p>\n\n<p>or simpler, you have an attribute called <code>current_post</code> just check if you're not in the first post, like this:</p>\n\n<pre><code>&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n&lt;?php \n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p><strong>Edit: I posted with the inverse logic, fixed now.</strong></p>\n" }, { "answer_id": 274499, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>The easiest thing is to add a counter variable to your loop. But also be sure to add a posts exists check to prevent issues if no posts are found and I highly recommend using good commenting and syntax - it's a good habit ;)</p>\n\n<p>Here is an example of the modified code:</p>\n\n<pre><code>&lt;?php\n// Query posts\n$homenews_query = new WP_Query( 'posts_per_page=4' );\n\n// If posts are found do stuff\nif ( $the_query-&gt;have_posts() ) :\n\n // Define counter\n $count = 0;\n\n // Loop through posts\n while ( $homenews_query-&gt;have_posts() ) : $homenews_query-&gt;the_post();\n\n // Add to counter for each entry\n $count ++;\n\n // Define default classname for entry\n $class = 'entry';\n\n // Add class name to all excerpt the first\n if ( 1 !== $count ) {\n $class .= ' first-post';\n }\n\n // Add odd/even classes\n $class .= $count % 2 == 0 ? ' even' : ' odd';\n\n\n // No posts found\n else: ?&gt;\n\n &lt;!-- stuff here --&gt;\n\n &lt;?php endif ?&gt;\n\n &lt;?php\n // End loop\n endwhile;\n\n // Reset post data to prevent query conflicts\n wp_reset_postdata(); \n\n// End posts check\nendif; ?&gt;\n</code></pre>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I have a simple columns shortcode. (How) can this be adjusted to output a containing div around multiple columns? Really don't want to nest shortcodes in the frontend. Perhaps some kind of filter? My `functions.php` looks like this: ``` // Columns shortcode function abc_custom_column( $atts, $content = null ) { return '<div class="column">' . do_shortcode( $content ) . '</div>'; } add_shortcode('col', 'abc_custom_column'); ``` Hoping for something like: ``` if ( 'col' === >2 ) { return '<div class="multi_columns">' . do_shortcode( $content ) . '</div>'; } else { return '<div class="column">' . do_shortcode( $content ) . '</div>'; } ``` \*\*\* I know that clearly won't work / isn't valid code.
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,518
<p>Whenever I search something on my wordpress site, I get the error:</p> <pre><code>Fatal error: Uncaught Error: Call to undefined function get_exID() in /var/www/html/wp-content/themes/twentyseventeen/functions.php:360 Stack trace: #0 /var/www/html/wp-includes/class-wp-hook.php(298): twentyseventeen_excerpt_more(' [&amp;hellip;]') #1 /var/www/html/wp- includes/plugin.php(203): WP_Hook-&gt;apply_filters(' [&amp;hellip;]', Array) #2 /var/www/html/wp-includes/formatting.php(3315): apply_filters('excerpt_more', ' [&amp;hellip;]') #3 /var/www/html/wp- includes/class-wp-hook.php(300): wp_trim_excerpt('&lt;p&gt;Today I will...') #4 /var/www/html/wp-includes/plugin.php(203): WP_Hook- &gt;apply_filters('', Array) #5 /var/www/html/wp-includes/post- template.php(397): apply_filters('get_the_excerpt', '', Object(WP_Post)) #6 /var/www/html/wp-includes/post-template.php(362): get_the_excerpt() #7 /var/www/html/wp- content/themes/twentyseventeen/template-parts/post/content- excerpt.php(43): the_excerpt() #8 /var/www/html/wp- includes/template.php(690): require('/var/www/html/w...') #9 /var/www/html/wp-includes/template.php(647): load_template('/var in /var/www/html/wp-content/themes/twentyseventeen/functions.php on line 360 </code></pre> <p>where the post summary is supposed to be. How can I fix it?</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:</p>\n\n<pre><code>&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>then in your <strong>css</strong>:</p>\n\n<pre><code>.post:not(:first-child) {\n // add the rules of the class you wanted to add\n}\n</code></pre>\n\n<p>Just select all elements except the first-child of posts with the class <code>post</code> and add the rules of the class you wanted to add.</p>\n\n<p>You also can do with <strong>js/jquery</strong>:</p>\n\n<pre><code>$('.post:not(:first-child)').addClass('myclass');\n</code></pre>\n\n<p>It's the same logic as with css, but if you wnat to add a separate class you can do it.</p>\n\n<p>or you can do with <strong>php</strong>:</p>\n\n<pre><code>&lt;?php $count = 0 ?&gt;\n&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($count != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n\n&lt;?php \n $count++;\n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>I know that the first post, is the one in the <code>index 0</code> so a just check if the count is != 0.</p>\n\n<p>or simpler, you have an attribute called <code>current_post</code> just check if you're not in the first post, like this:</p>\n\n<pre><code>&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n&lt;?php \n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p><strong>Edit: I posted with the inverse logic, fixed now.</strong></p>\n" }, { "answer_id": 274499, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>The easiest thing is to add a counter variable to your loop. But also be sure to add a posts exists check to prevent issues if no posts are found and I highly recommend using good commenting and syntax - it's a good habit ;)</p>\n\n<p>Here is an example of the modified code:</p>\n\n<pre><code>&lt;?php\n// Query posts\n$homenews_query = new WP_Query( 'posts_per_page=4' );\n\n// If posts are found do stuff\nif ( $the_query-&gt;have_posts() ) :\n\n // Define counter\n $count = 0;\n\n // Loop through posts\n while ( $homenews_query-&gt;have_posts() ) : $homenews_query-&gt;the_post();\n\n // Add to counter for each entry\n $count ++;\n\n // Define default classname for entry\n $class = 'entry';\n\n // Add class name to all excerpt the first\n if ( 1 !== $count ) {\n $class .= ' first-post';\n }\n\n // Add odd/even classes\n $class .= $count % 2 == 0 ? ' even' : ' odd';\n\n\n // No posts found\n else: ?&gt;\n\n &lt;!-- stuff here --&gt;\n\n &lt;?php endif ?&gt;\n\n &lt;?php\n // End loop\n endwhile;\n\n // Reset post data to prevent query conflicts\n wp_reset_postdata(); \n\n// End posts check\nendif; ?&gt;\n</code></pre>\n" } ]
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274518", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
Whenever I search something on my wordpress site, I get the error: ``` Fatal error: Uncaught Error: Call to undefined function get_exID() in /var/www/html/wp-content/themes/twentyseventeen/functions.php:360 Stack trace: #0 /var/www/html/wp-includes/class-wp-hook.php(298): twentyseventeen_excerpt_more(' [&hellip;]') #1 /var/www/html/wp- includes/plugin.php(203): WP_Hook->apply_filters(' [&hellip;]', Array) #2 /var/www/html/wp-includes/formatting.php(3315): apply_filters('excerpt_more', ' [&hellip;]') #3 /var/www/html/wp- includes/class-wp-hook.php(300): wp_trim_excerpt('<p>Today I will...') #4 /var/www/html/wp-includes/plugin.php(203): WP_Hook- >apply_filters('', Array) #5 /var/www/html/wp-includes/post- template.php(397): apply_filters('get_the_excerpt', '', Object(WP_Post)) #6 /var/www/html/wp-includes/post-template.php(362): get_the_excerpt() #7 /var/www/html/wp- content/themes/twentyseventeen/template-parts/post/content- excerpt.php(43): the_excerpt() #8 /var/www/html/wp- includes/template.php(690): require('/var/www/html/w...') #9 /var/www/html/wp-includes/template.php(647): load_template('/var in /var/www/html/wp-content/themes/twentyseventeen/functions.php on line 360 ``` where the post summary is supposed to be. How can I fix it?
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,553
<p>I am new to WordPress development. After develops a simple from the scratch everything works fine. Now I want to create a custom page template to show case all e-books with a just thumbnail of the cover and the price. To brief description, I want to redirect to a particular page. It's all like from the Blog list to particular blog page.</p> <p>I created the custom page with specific style. Now my problem is I don't know how to redirect to its particular page for purchase.</p> <p>How do I do that? Any instruction will be helpful. Thanks in Advance.</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:</p>\n\n<pre><code>&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n&lt;div class=\"post\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>then in your <strong>css</strong>:</p>\n\n<pre><code>.post:not(:first-child) {\n // add the rules of the class you wanted to add\n}\n</code></pre>\n\n<p>Just select all elements except the first-child of posts with the class <code>post</code> and add the rules of the class you wanted to add.</p>\n\n<p>You also can do with <strong>js/jquery</strong>:</p>\n\n<pre><code>$('.post:not(:first-child)').addClass('myclass');\n</code></pre>\n\n<p>It's the same logic as with css, but if you wnat to add a separate class you can do it.</p>\n\n<p>or you can do with <strong>php</strong>:</p>\n\n<pre><code>&lt;?php $count = 0 ?&gt;\n&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($count != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n\n&lt;?php \n $count++;\n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>I know that the first post, is the one in the <code>index 0</code> so a just check if the count is != 0.</p>\n\n<p>or simpler, you have an attribute called <code>current_post</code> just check if you're not in the first post, like this:</p>\n\n<pre><code>&lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post != 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php endif ?&gt;\n\n&lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt;\n &lt;!-- stuff here --&gt;\n&lt;?php else: ?&gt;\n &lt;!-- stuff here --&gt; \n&lt;?php endif ?&gt;\n&lt;?php \n endwhile;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p><strong>Edit: I posted with the inverse logic, fixed now.</strong></p>\n" }, { "answer_id": 274499, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>The easiest thing is to add a counter variable to your loop. But also be sure to add a posts exists check to prevent issues if no posts are found and I highly recommend using good commenting and syntax - it's a good habit ;)</p>\n\n<p>Here is an example of the modified code:</p>\n\n<pre><code>&lt;?php\n// Query posts\n$homenews_query = new WP_Query( 'posts_per_page=4' );\n\n// If posts are found do stuff\nif ( $the_query-&gt;have_posts() ) :\n\n // Define counter\n $count = 0;\n\n // Loop through posts\n while ( $homenews_query-&gt;have_posts() ) : $homenews_query-&gt;the_post();\n\n // Add to counter for each entry\n $count ++;\n\n // Define default classname for entry\n $class = 'entry';\n\n // Add class name to all excerpt the first\n if ( 1 !== $count ) {\n $class .= ' first-post';\n }\n\n // Add odd/even classes\n $class .= $count % 2 == 0 ? ' even' : ' odd';\n\n\n // No posts found\n else: ?&gt;\n\n &lt;!-- stuff here --&gt;\n\n &lt;?php endif ?&gt;\n\n &lt;?php\n // End loop\n endwhile;\n\n // Reset post data to prevent query conflicts\n wp_reset_postdata(); \n\n// End posts check\nendif; ?&gt;\n</code></pre>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124542/" ]
I am new to WordPress development. After develops a simple from the scratch everything works fine. Now I want to create a custom page template to show case all e-books with a just thumbnail of the cover and the price. To brief description, I want to redirect to a particular page. It's all like from the Blog list to particular blog page. I created the custom page with specific style. Now my problem is I don't know how to redirect to its particular page for purchase. How do I do that? Any instruction will be helpful. Thanks in Advance.
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,559
<p>I'm coding a plugin that adds a filter to <code>single_template</code>. The filter function successfully returns the path to my <code>show-post-in-a-lightbox.php</code> template.</p> <p>As you can guess from its name, my template is intended to show a single post in a lightbox. Therefore I need to show only the post content and avoid the title bar, menus, sidebars, footers and so on. However, for the post content to show correctly, I need the usual <code>&lt;head&gt;</code> section with all the <code>&lt;link&gt;</code> tags to the required stylesheets and <code>&lt;script&gt;</code> tags.</p> <p>My template code so far is:</p> <pre><code>&lt;?php /* Template Name: show-post-in-lightbox * */ get_header(); ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;?php global $post; // Start the loop. while ( have_posts() ) : the_post(); $content = $post-&gt;post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]&gt;', ']]&amp;gt;', $content); echo $content; </code></pre> <p>This works in that it shows the post content, but it also shows the heading banner above it, with the site logo, the title (I'm not talking about <code>&lt;title&gt;</code>, that one is ok, but I mean <code>&lt;header id="masthead" class="site-header"&gt;</code>), and all the rest therein.</p> <p>If I comment out the <code>get_header();</code> line it outputs only the content, but without the required styles and scripts.</p> <p>Is there a function that returns (or outputs) only the <code>&lt;head&gt;</code> tag (or only up to the <code>&lt;/head&gt;</code> tag) of a given post?</p>
[ { "answer_id": 274562, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>wp_head()</code> function, you just need to add the opening <code>html</code> and <code>body</code> tags, and the head tags:</p>\n\n<pre><code>&lt;?php\n/*\n * Template Name: show-post-in-lightbox\n */\n?&gt;\n&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n\n&lt;!-- Content here --&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>If your footer closes any elements/divs other than <code>html</code> and <code>body</code>, make sure to open them in this template.</p>\n\n<p>Also, <code>wp_head()</code> doesn't necessarily include <em>everything</em> in the head element, check your theme's header.php file. It should have the <code>wp_head()</code> function itself, just check for anything that was added separately that you might need to include in the <code>head</code>.</p>\n\n<p>Another option would be to copy header.php, rename it something like header-post.php, remove everything you don't want to appear on posts, and then in your cutstom template, use <code>get_header( 'post' );</code> to use that version of the header:</p>\n\n<pre><code>&lt;?php\n/*\n * Template Name: show-post-in-lightbox\n */\n\nget_header( 'post' ); ?&gt;\n\n&lt;!-- Post content here --&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n" }, { "answer_id": 274586, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Front end styling is usually a theme territory that plugins should avoid. There is no simple way to know how anything is styled without actually doing the full styling, as some of it will depend on the content itself, and since the styling is basically random from the plugin author POV, you are unlikely to be able to have a general algorithm to adjust it to whatever you need in a reliable way.</p>\n\n<p>Best approach that comes into my mind is to wrap the content with your own div, and use JS to hide everything else on the page. Still you will most likely get a mobile type of vies in your lightbox, which might not be what you are after.</p>\n" }, { "answer_id": 274834, "author": "Lucio Crusca", "author_id": 84622, "author_profile": "https://wordpress.stackexchange.com/users/84622", "pm_score": -1, "selected": true, "text": "<p>I've finally ended up with something similar to what Mark Kaplun had suggested in his answer, but, instead of using JS code, I opted for a CSS solution instead.</p>\n\n<p>When my code creates the <code>&lt;iframe&gt;</code> link, it appends a extra HTTP parameter:</p>\n\n<pre><code>$lightboxlink = '/?p='.$postid.'&amp;use-lightbox-css=1';\n</code></pre>\n\n<p>Then the plugin checks for that parameter, and, if present, it enqueues the extra CSS file.</p>\n\n<p>And here is the CSS file contents:</p>\n\n<pre><code>header {\n display: none !important;\n}\n</code></pre>\n\n<p>I know, I shouldn't be using <code>!important</code>. To avoid that, the plugin uses the lowest possible prority (PHP_INT_MAX) to the <code>add_action</code> call that register my function with the <code>wp_enqueue_style</code> call. That way, my extra CSS is loaded as the last one inside the <code>&lt;iframe&gt;</code> tag and it takes precedence over all the others (that's the <code>Cascading</code> meaning of CSS). Now I can strip the <code>!important</code>:</p>\n\n<pre><code>header {\n display: none;\n}\n</code></pre>\n\n<p>That works only with themes that actually make use of the <code>&lt;header&gt;</code> tag, but for now it's good enough for my use cases. Anyway adapting it to other themes is only a matter of adding the required selectors to the CSS file, for example here is a first guess for the Wiz theme that I sometimes use:</p>\n\n<pre><code>header, .header-vh-wrapper, .navbar-inner, .nav-container, .logo, #title {\n display: none;\n}\n</code></pre>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm coding a plugin that adds a filter to `single_template`. The filter function successfully returns the path to my `show-post-in-a-lightbox.php` template. As you can guess from its name, my template is intended to show a single post in a lightbox. Therefore I need to show only the post content and avoid the title bar, menus, sidebars, footers and so on. However, for the post content to show correctly, I need the usual `<head>` section with all the `<link>` tags to the required stylesheets and `<script>` tags. My template code so far is: ``` <?php /* Template Name: show-post-in-lightbox * */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php global $post; // Start the loop. while ( have_posts() ) : the_post(); $content = $post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); echo $content; ``` This works in that it shows the post content, but it also shows the heading banner above it, with the site logo, the title (I'm not talking about `<title>`, that one is ok, but I mean `<header id="masthead" class="site-header">`), and all the rest therein. If I comment out the `get_header();` line it outputs only the content, but without the required styles and scripts. Is there a function that returns (or outputs) only the `<head>` tag (or only up to the `</head>` tag) of a given post?
I've finally ended up with something similar to what Mark Kaplun had suggested in his answer, but, instead of using JS code, I opted for a CSS solution instead. When my code creates the `<iframe>` link, it appends a extra HTTP parameter: ``` $lightboxlink = '/?p='.$postid.'&use-lightbox-css=1'; ``` Then the plugin checks for that parameter, and, if present, it enqueues the extra CSS file. And here is the CSS file contents: ``` header { display: none !important; } ``` I know, I shouldn't be using `!important`. To avoid that, the plugin uses the lowest possible prority (PHP\_INT\_MAX) to the `add_action` call that register my function with the `wp_enqueue_style` call. That way, my extra CSS is loaded as the last one inside the `<iframe>` tag and it takes precedence over all the others (that's the `Cascading` meaning of CSS). Now I can strip the `!important`: ``` header { display: none; } ``` That works only with themes that actually make use of the `<header>` tag, but for now it's good enough for my use cases. Anyway adapting it to other themes is only a matter of adding the required selectors to the CSS file, for example here is a first guess for the Wiz theme that I sometimes use: ``` header, .header-vh-wrapper, .navbar-inner, .nav-container, .logo, #title { display: none; } ```
274,561
<p>I created text widget and wordpress created some default styles it uses h2 tag and class "widgettitle". How can i change tag to h1 and remove class from it.</p> <p>This is my function.php file</p> <pre><code>function home_consultation_init() { register_sidebar(array( "name" =&gt; "Home Consulatation", "id" =&gt; "home_consult", "before_widget" =&gt; "", "after_widget" =&gt; "", "before-title" =&gt; "", "after-title" =&gt; "" )); } </code></pre>
[ { "answer_id": 274566, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>The <code>before-title</code> and <code>after-title</code> arguments passed to <code>register_sidebar()</code> need to use underscores:</p>\n\n<pre><code>register_sidebar(array(\n \"name\" =&gt; \"Home Consulatation\",\n \"id\" =&gt; \"home_consult\",\n \"before_widget\" =&gt; \"\",\n \"after_widget\" =&gt; \"\",\n \"before_title\" =&gt; \"\",\n \"after_title\" =&gt; \"\"\n));\n</code></pre>\n\n<p>If you use that the titles won't have any tags. You need to provide them to the <code>before_title</code> and <code>after_title</code> arguments, like so:</p>\n\n<pre><code>register_sidebar(array(\n \"name\" =&gt; \"Home Consulatation\",\n \"id\" =&gt; \"home_consult\",\n \"before_widget\" =&gt; \"\",\n \"after_widget\" =&gt; \"\",\n \"before_title\" =&gt; \"&lt;h1&gt;\",\n \"after_title\" =&gt; \"&lt;/h1&gt;\"\n));\n</code></pre>\n\n<p>Your problem was that you were using the incorrect keys (with <code>-</code> instead of <code>_</code>), so it was using the defaults.</p>\n" }, { "answer_id": 274567, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 1, "selected": false, "text": "<p>widget title h2 to h1 change you have change in <strong>where you register widgets</strong>. two arguments \"before_title\" and \"after_title\".</p>\n\n<pre><code>register_sidebar( array(\n 'name' =&gt; esc_html__( 'Sidebar', 'themeName' ),\n 'id' =&gt; 'sidebar-1',\n 'description' =&gt; '',\n 'before_widget' =&gt; '&lt;section id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/section&gt;',\n 'before_title' =&gt; '&lt;h1 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h1&gt;',\n ) ); \n</code></pre>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274561", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124458/" ]
I created text widget and wordpress created some default styles it uses h2 tag and class "widgettitle". How can i change tag to h1 and remove class from it. This is my function.php file ``` function home_consultation_init() { register_sidebar(array( "name" => "Home Consulatation", "id" => "home_consult", "before_widget" => "", "after_widget" => "", "before-title" => "", "after-title" => "" )); } ```
The `before-title` and `after-title` arguments passed to `register_sidebar()` need to use underscores: ``` register_sidebar(array( "name" => "Home Consulatation", "id" => "home_consult", "before_widget" => "", "after_widget" => "", "before_title" => "", "after_title" => "" )); ``` If you use that the titles won't have any tags. You need to provide them to the `before_title` and `after_title` arguments, like so: ``` register_sidebar(array( "name" => "Home Consulatation", "id" => "home_consult", "before_widget" => "", "after_widget" => "", "before_title" => "<h1>", "after_title" => "</h1>" )); ``` Your problem was that you were using the incorrect keys (with `-` instead of `_`), so it was using the defaults.
274,569
<p>I want to add custom PHP code to ensure that whenever a page on my site loads in my browser, the URL of that page is echoed to the screen. I can use <code>echo get_permalink()</code>, but that does not work on all pages. Some pages (e.g. <a href="https://www.horizonhomes-samui.com/" rel="noreferrer">my homepage</a>) display several posts, and if I use <code>get_permalink()</code> on these pages, the URL of the displayed page is not returned (I believe it returns the URL of the last post in the loop). For these pages, how can I return the URL?</p> <p>Can I attach <code>get_permalink()</code> to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete?</p> <p>Thanks.</p>
[ { "answer_id": 274572, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 9, "selected": true, "text": "<p><code>get_permalink()</code> is only really useful for single pages and posts, and only works inside the loop.</p>\n\n<p>The simplest way I've seen is this:</p>\n\n<pre><code>global $wp;\necho home_url( $wp-&gt;request )\n</code></pre>\n\n<p><code>$wp-&gt;request</code> includes the path part of the URL, eg. <code>/path/to/page</code> and <code>home_url()</code> outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code.</p>\n\n<p>Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the <code>?foo=bar</code> part of the URL).</p>\n\n<p>To get the URL when permalinks are set to plain you can use <code>$wp-&gt;query_vars</code> instead, by passing it to <code>add_query_arg()</code>:</p>\n\n<pre><code>global $wp;\necho add_query_arg( $wp-&gt;query_vars, home_url() );\n</code></pre>\n\n<p>And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings:</p>\n\n<pre><code>global $wp;\necho add_query_arg( $wp-&gt;query_vars, home_url( $wp-&gt;request ) );\n</code></pre>\n" }, { "answer_id": 299898, "author": "rescue1155", "author_id": 141186, "author_profile": "https://wordpress.stackexchange.com/users/141186", "pm_score": 5, "selected": false, "text": "<p>You may use the below code to get the whole current URL in WordPress:</p>\n\n<pre><code>global $wp;\n$current_url = home_url(add_query_arg(array(), $wp-&gt;request));\n</code></pre>\n\n<p>This will show the full path, including query parameters.</p>\n" }, { "answer_id": 305852, "author": "tolginho", "author_id": 10090, "author_profile": "https://wordpress.stackexchange.com/users/10090", "pm_score": 1, "selected": false, "text": "<p>This is an improved way of example that mentioned previously. It works when pretty URLs are enabled however it discards if there is any query parameter like <strong>/page-slug/?param=1</strong> or URL is ugly at all.</p>\n\n<p>Following example will work on both cases.</p>\n\n<pre><code> $query_args = array();\n\n $query = wp_parse_url( $YOUR_URL );\n\n $permalink = get_option( 'permalink_structure' );\n\n if ( empty( $permalink ) ) {\n\n $query_args = $query['query'];\n\n }\n\n echo home_url( add_query_arg( $query_args , $wp-&gt;request ) )\n</code></pre>\n" }, { "answer_id": 320549, "author": "Shree Sthapit", "author_id": 154948, "author_profile": "https://wordpress.stackexchange.com/users/154948", "pm_score": 2, "selected": false, "text": "<pre><code>function current_location()\n{\n if (isset($_SERVER['HTTPS']) &amp;&amp;\n ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||\n isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &amp;&amp;\n $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {\n $protocol = 'https://';\n } else {\n $protocol = 'http://';\n }\n return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n}\n\necho current_location();\n</code></pre>\n" }, { "answer_id": 324032, "author": "Adiyya Tadikamalla", "author_id": 157219, "author_profile": "https://wordpress.stackexchange.com/users/157219", "pm_score": 3, "selected": false, "text": "<p>The following code will give the current URL:</p>\n\n<pre><code>global $wp;\necho home_url($wp-&gt;request)\n</code></pre>\n\n<p>You can use the below code to get the full URL along with query parameters.</p>\n\n<pre><code>global $wp; \n$current_url = home_url(add_query_arg(array($_GET), $wp-&gt;request));\n</code></pre>\n\n<p>This will show the full path, including query parameters. This will preserve query parameters if already in the URL.</p>\n" }, { "answer_id": 349469, "author": "Flow", "author_id": 43969, "author_profile": "https://wordpress.stackexchange.com/users/43969", "pm_score": 1, "selected": false, "text": "<p>Maybe <a href=\"https://developer.wordpress.org/reference/functions/wp_guess_url/\" rel=\"nofollow noreferrer\"><code>wp_guess_url()</code></a> is what you need. Available since version 2.6.0.</p>\n" }, { "answer_id": 350973, "author": "Dario Zadro", "author_id": 17126, "author_profile": "https://wordpress.stackexchange.com/users/17126", "pm_score": 4, "selected": false, "text": "<p>Why not just use?</p>\n<pre><code>get_permalink( get_the_ID() );\n</code></pre>\n<p>That is for single pages.</p>\n<p>For category pages, use this:</p>\n<pre><code>get_category_link( get_query_var( 'cat' ) );\n</code></pre>\n<p>Simple script to get the current URL of any page:</p>\n<pre><code>// get current URL \n$current_url = get_permalink( get_the_ID() );\nif( is_category() ) $current_url = get_category_link( get_query_var( 'cat' ) );\necho $current_url;\n \n</code></pre>\n" }, { "answer_id": 363252, "author": "Jonas Lundman", "author_id": 43172, "author_profile": "https://wordpress.stackexchange.com/users/43172", "pm_score": 1, "selected": false, "text": "<p>After so much research of a simple task, a mix of all answers above works for us: </p>\n\n<pre><code>function get_wp_current_url(){\n global $wp;\n if('' === get_option('permalink_structure')) return home_url(add_query_arg(array($_GET), $wp-&gt;request));\n else return home_url(trailingslashit(add_query_arg(array($_GET), $wp-&gt;request)));\n}\n</code></pre>\n\n<p>No missing slash at the end and so on. As the question id about output the current url, this doesnt care about security and stuff. However, hash like #comment at the end cant be found in PHP.</p>\n" }, { "answer_id": 371139, "author": "Imran Zahoor", "author_id": 73699, "author_profile": "https://wordpress.stackexchange.com/users/73699", "pm_score": 1, "selected": false, "text": "<p>This is what worked for me (short and clean solution that includes the query strings in the URL too):</p>\n<pre><code>$current_url = add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp-&gt;request ) );\n</code></pre>\n<p>The output URL will look like below</p>\n<pre><code>http://sometesturl.test/slug1/slug2?queryParam1=testing&amp;queryParam2=123\n</code></pre>\n<p>The solution was taken from <a href=\"https://gist.github.com/leereamsnyder/fac3b9ccb6b99ab14f36\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 371909, "author": "Hybrid Web Dev", "author_id": 36506, "author_profile": "https://wordpress.stackexchange.com/users/36506", "pm_score": 1, "selected": false, "text": "<p>I realize this is an old question, however one thing I've noticed is no-one mentioned using <code>get_queried_object()</code>.</p>\n<p>It's a global wp function that grabs whatever relates to the current url you're on. So for instance if you're on a page or post, it'll return a post object. If you're on an archive it will return a post type object.</p>\n<p>WP also has a bunch of helper functions, like <code>get_post_type_archive_link</code> that you can give the objects post type field to and get back its link like so</p>\n<pre><code>get_post_type_archive_link(get_queried_object()-&gt;name);\n</code></pre>\n<p>The point is, you don't need to rely on some of the hackier answers above, and instead use the queried object to always get the correct url.</p>\n<p>This will also work for multisite installs with no extra work, as by using wp's functions, you're always getting the correct url.</p>\n" }, { "answer_id": 379617, "author": "Akmal", "author_id": 165190, "author_profile": "https://wordpress.stackexchange.com/users/165190", "pm_score": 4, "selected": false, "text": "<p>In my case, this code worked fine:</p>\n<pre><code>$current_url = home_url($_SERVER['REQUEST_URI'])\n</code></pre>\n<p>I hope it will help someone, I tried all answers but this one was helpful.</p>\n" }, { "answer_id": 381422, "author": "Bawm", "author_id": 200276, "author_profile": "https://wordpress.stackexchange.com/users/200276", "pm_score": 2, "selected": false, "text": "<pre><code>global $wp;\n$wp-&gt;parse_request();\n$current_url = home_url($wp-&gt;request);\n</code></pre>\n" }, { "answer_id": 388894, "author": "Rodgath", "author_id": 158083, "author_profile": "https://wordpress.stackexchange.com/users/158083", "pm_score": 2, "selected": false, "text": "<p>The solutions here are all good but were not consistent with both local and remote server environments. So I came up with a simpler neat solution that works better <strong>regardless of the WordPress permalink settings</strong>.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function getCurrentUrl() {\n $protocol = is_ssl() ? 'https://' : 'http://';\n return ($protocol) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$currentUrl = getCurrentUrl();\necho $currentUrl;\n</code></pre>\n<p>The output will include URL query parameters and slugs.</p>\n" }, { "answer_id": 397466, "author": "Ivan Ivan", "author_id": 214196, "author_profile": "https://wordpress.stackexchange.com/users/214196", "pm_score": 1, "selected": false, "text": "<p>WP updated something and now the <strong>property</strong> request of the global <strong>$wp</strong> is empty by default. You must call the special method <strong><a href=\"https://github.com/WordPress/WordPress/blob/5ca2a817abb025a01bf9a8056ed00c766f7e6eed/wp-includes/class-wp.php#L133-L397\" rel=\"nofollow noreferrer\">parse_request</a></strong> before to get data of this property.</p>\n<p>So it was this way:</p>\n<pre><code>global $wp;\necho home_url( $wp-&gt;request );\n</code></pre>\n<p>Now it should be the next way:</p>\n<pre><code>global $wp;\n$wp-&gt;parse_request();\necho home_url( $wp-&gt;request );\n</code></pre>\n<p>P.S. I'd like to leave in comments under the most popular response, but I don't permissions to leave comments.</p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I want to add custom PHP code to ensure that whenever a page on my site loads in my browser, the URL of that page is echoed to the screen. I can use `echo get_permalink()`, but that does not work on all pages. Some pages (e.g. [my homepage](https://www.horizonhomes-samui.com/)) display several posts, and if I use `get_permalink()` on these pages, the URL of the displayed page is not returned (I believe it returns the URL of the last post in the loop). For these pages, how can I return the URL? Can I attach `get_permalink()` to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete? Thanks.
`get_permalink()` is only really useful for single pages and posts, and only works inside the loop. The simplest way I've seen is this: ``` global $wp; echo home_url( $wp->request ) ``` `$wp->request` includes the path part of the URL, eg. `/path/to/page` and `home_url()` outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code. Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the `?foo=bar` part of the URL). To get the URL when permalinks are set to plain you can use `$wp->query_vars` instead, by passing it to `add_query_arg()`: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url() ); ``` And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url( $wp->request ) ); ```
274,576
<p>I am having a problem when creating scheduled posts. I create the posts as normal, click edit, set a scheduled time and click ok then the shedual button. Soon as i do this i check the website and the post has been published immediately. I looked back in the view all posts page and the post says its still scheduled. It was working fine for months but suddenly this is occurring. Really need this sorting asap! cheers</p>
[ { "answer_id": 274572, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 9, "selected": true, "text": "<p><code>get_permalink()</code> is only really useful for single pages and posts, and only works inside the loop.</p>\n\n<p>The simplest way I've seen is this:</p>\n\n<pre><code>global $wp;\necho home_url( $wp-&gt;request )\n</code></pre>\n\n<p><code>$wp-&gt;request</code> includes the path part of the URL, eg. <code>/path/to/page</code> and <code>home_url()</code> outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code.</p>\n\n<p>Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the <code>?foo=bar</code> part of the URL).</p>\n\n<p>To get the URL when permalinks are set to plain you can use <code>$wp-&gt;query_vars</code> instead, by passing it to <code>add_query_arg()</code>:</p>\n\n<pre><code>global $wp;\necho add_query_arg( $wp-&gt;query_vars, home_url() );\n</code></pre>\n\n<p>And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings:</p>\n\n<pre><code>global $wp;\necho add_query_arg( $wp-&gt;query_vars, home_url( $wp-&gt;request ) );\n</code></pre>\n" }, { "answer_id": 299898, "author": "rescue1155", "author_id": 141186, "author_profile": "https://wordpress.stackexchange.com/users/141186", "pm_score": 5, "selected": false, "text": "<p>You may use the below code to get the whole current URL in WordPress:</p>\n\n<pre><code>global $wp;\n$current_url = home_url(add_query_arg(array(), $wp-&gt;request));\n</code></pre>\n\n<p>This will show the full path, including query parameters.</p>\n" }, { "answer_id": 305852, "author": "tolginho", "author_id": 10090, "author_profile": "https://wordpress.stackexchange.com/users/10090", "pm_score": 1, "selected": false, "text": "<p>This is an improved way of example that mentioned previously. It works when pretty URLs are enabled however it discards if there is any query parameter like <strong>/page-slug/?param=1</strong> or URL is ugly at all.</p>\n\n<p>Following example will work on both cases.</p>\n\n<pre><code> $query_args = array();\n\n $query = wp_parse_url( $YOUR_URL );\n\n $permalink = get_option( 'permalink_structure' );\n\n if ( empty( $permalink ) ) {\n\n $query_args = $query['query'];\n\n }\n\n echo home_url( add_query_arg( $query_args , $wp-&gt;request ) )\n</code></pre>\n" }, { "answer_id": 320549, "author": "Shree Sthapit", "author_id": 154948, "author_profile": "https://wordpress.stackexchange.com/users/154948", "pm_score": 2, "selected": false, "text": "<pre><code>function current_location()\n{\n if (isset($_SERVER['HTTPS']) &amp;&amp;\n ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||\n isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &amp;&amp;\n $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {\n $protocol = 'https://';\n } else {\n $protocol = 'http://';\n }\n return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n}\n\necho current_location();\n</code></pre>\n" }, { "answer_id": 324032, "author": "Adiyya Tadikamalla", "author_id": 157219, "author_profile": "https://wordpress.stackexchange.com/users/157219", "pm_score": 3, "selected": false, "text": "<p>The following code will give the current URL:</p>\n\n<pre><code>global $wp;\necho home_url($wp-&gt;request)\n</code></pre>\n\n<p>You can use the below code to get the full URL along with query parameters.</p>\n\n<pre><code>global $wp; \n$current_url = home_url(add_query_arg(array($_GET), $wp-&gt;request));\n</code></pre>\n\n<p>This will show the full path, including query parameters. This will preserve query parameters if already in the URL.</p>\n" }, { "answer_id": 349469, "author": "Flow", "author_id": 43969, "author_profile": "https://wordpress.stackexchange.com/users/43969", "pm_score": 1, "selected": false, "text": "<p>Maybe <a href=\"https://developer.wordpress.org/reference/functions/wp_guess_url/\" rel=\"nofollow noreferrer\"><code>wp_guess_url()</code></a> is what you need. Available since version 2.6.0.</p>\n" }, { "answer_id": 350973, "author": "Dario Zadro", "author_id": 17126, "author_profile": "https://wordpress.stackexchange.com/users/17126", "pm_score": 4, "selected": false, "text": "<p>Why not just use?</p>\n<pre><code>get_permalink( get_the_ID() );\n</code></pre>\n<p>That is for single pages.</p>\n<p>For category pages, use this:</p>\n<pre><code>get_category_link( get_query_var( 'cat' ) );\n</code></pre>\n<p>Simple script to get the current URL of any page:</p>\n<pre><code>// get current URL \n$current_url = get_permalink( get_the_ID() );\nif( is_category() ) $current_url = get_category_link( get_query_var( 'cat' ) );\necho $current_url;\n \n</code></pre>\n" }, { "answer_id": 363252, "author": "Jonas Lundman", "author_id": 43172, "author_profile": "https://wordpress.stackexchange.com/users/43172", "pm_score": 1, "selected": false, "text": "<p>After so much research of a simple task, a mix of all answers above works for us: </p>\n\n<pre><code>function get_wp_current_url(){\n global $wp;\n if('' === get_option('permalink_structure')) return home_url(add_query_arg(array($_GET), $wp-&gt;request));\n else return home_url(trailingslashit(add_query_arg(array($_GET), $wp-&gt;request)));\n}\n</code></pre>\n\n<p>No missing slash at the end and so on. As the question id about output the current url, this doesnt care about security and stuff. However, hash like #comment at the end cant be found in PHP.</p>\n" }, { "answer_id": 371139, "author": "Imran Zahoor", "author_id": 73699, "author_profile": "https://wordpress.stackexchange.com/users/73699", "pm_score": 1, "selected": false, "text": "<p>This is what worked for me (short and clean solution that includes the query strings in the URL too):</p>\n<pre><code>$current_url = add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp-&gt;request ) );\n</code></pre>\n<p>The output URL will look like below</p>\n<pre><code>http://sometesturl.test/slug1/slug2?queryParam1=testing&amp;queryParam2=123\n</code></pre>\n<p>The solution was taken from <a href=\"https://gist.github.com/leereamsnyder/fac3b9ccb6b99ab14f36\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 371909, "author": "Hybrid Web Dev", "author_id": 36506, "author_profile": "https://wordpress.stackexchange.com/users/36506", "pm_score": 1, "selected": false, "text": "<p>I realize this is an old question, however one thing I've noticed is no-one mentioned using <code>get_queried_object()</code>.</p>\n<p>It's a global wp function that grabs whatever relates to the current url you're on. So for instance if you're on a page or post, it'll return a post object. If you're on an archive it will return a post type object.</p>\n<p>WP also has a bunch of helper functions, like <code>get_post_type_archive_link</code> that you can give the objects post type field to and get back its link like so</p>\n<pre><code>get_post_type_archive_link(get_queried_object()-&gt;name);\n</code></pre>\n<p>The point is, you don't need to rely on some of the hackier answers above, and instead use the queried object to always get the correct url.</p>\n<p>This will also work for multisite installs with no extra work, as by using wp's functions, you're always getting the correct url.</p>\n" }, { "answer_id": 379617, "author": "Akmal", "author_id": 165190, "author_profile": "https://wordpress.stackexchange.com/users/165190", "pm_score": 4, "selected": false, "text": "<p>In my case, this code worked fine:</p>\n<pre><code>$current_url = home_url($_SERVER['REQUEST_URI'])\n</code></pre>\n<p>I hope it will help someone, I tried all answers but this one was helpful.</p>\n" }, { "answer_id": 381422, "author": "Bawm", "author_id": 200276, "author_profile": "https://wordpress.stackexchange.com/users/200276", "pm_score": 2, "selected": false, "text": "<pre><code>global $wp;\n$wp-&gt;parse_request();\n$current_url = home_url($wp-&gt;request);\n</code></pre>\n" }, { "answer_id": 388894, "author": "Rodgath", "author_id": 158083, "author_profile": "https://wordpress.stackexchange.com/users/158083", "pm_score": 2, "selected": false, "text": "<p>The solutions here are all good but were not consistent with both local and remote server environments. So I came up with a simpler neat solution that works better <strong>regardless of the WordPress permalink settings</strong>.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function getCurrentUrl() {\n $protocol = is_ssl() ? 'https://' : 'http://';\n return ($protocol) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$currentUrl = getCurrentUrl();\necho $currentUrl;\n</code></pre>\n<p>The output will include URL query parameters and slugs.</p>\n" }, { "answer_id": 397466, "author": "Ivan Ivan", "author_id": 214196, "author_profile": "https://wordpress.stackexchange.com/users/214196", "pm_score": 1, "selected": false, "text": "<p>WP updated something and now the <strong>property</strong> request of the global <strong>$wp</strong> is empty by default. You must call the special method <strong><a href=\"https://github.com/WordPress/WordPress/blob/5ca2a817abb025a01bf9a8056ed00c766f7e6eed/wp-includes/class-wp.php#L133-L397\" rel=\"nofollow noreferrer\">parse_request</a></strong> before to get data of this property.</p>\n<p>So it was this way:</p>\n<pre><code>global $wp;\necho home_url( $wp-&gt;request );\n</code></pre>\n<p>Now it should be the next way:</p>\n<pre><code>global $wp;\n$wp-&gt;parse_request();\necho home_url( $wp-&gt;request );\n</code></pre>\n<p>P.S. I'd like to leave in comments under the most popular response, but I don't permissions to leave comments.</p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122305/" ]
I am having a problem when creating scheduled posts. I create the posts as normal, click edit, set a scheduled time and click ok then the shedual button. Soon as i do this i check the website and the post has been published immediately. I looked back in the view all posts page and the post says its still scheduled. It was working fine for months but suddenly this is occurring. Really need this sorting asap! cheers
`get_permalink()` is only really useful for single pages and posts, and only works inside the loop. The simplest way I've seen is this: ``` global $wp; echo home_url( $wp->request ) ``` `$wp->request` includes the path part of the URL, eg. `/path/to/page` and `home_url()` outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code. Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the `?foo=bar` part of the URL). To get the URL when permalinks are set to plain you can use `$wp->query_vars` instead, by passing it to `add_query_arg()`: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url() ); ``` And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url( $wp->request ) ); ```
274,589
<p>I have a code for display recent posts: </p> <p><code>&lt;?php $args = array( 'numberposts' =&gt; '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '&lt;h2&gt;&lt;a href="' . get_permalink($recent["ID"]) . '"&gt;' . $recent["post_title"].'&lt;/a&gt; &lt;/h2&gt; '; echo '&lt;p&gt;' . date_i18n('d F Y', strtotime($recent['post_date'])) .'&lt;/p&gt; '; // what code here? } wp_reset_query(); ?&gt;</code></p> <p>now I want to display category name and link also. What kind of code should I use in here? I try some but without effect...</p> <p>Thx :)</p>
[ { "answer_id": 274591, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_category_list\" rel=\"nofollow noreferrer\"><code>get_the_category_list()</code></a> to output a comma-separated list of links to categories:</p>\n\n<pre><code>&lt;?php\n $args = array( 'numberposts' =&gt; '5' );\n $recent_posts = wp_get_recent_posts( $args );\n foreach( $recent_posts as $recent ){\n echo '&lt;h2&gt;&lt;a href=\"' . get_permalink($recent[\"ID\"]) . '\"&gt;' . $recent[\"post_title\"].'&lt;/a&gt; &lt;/h2&gt; ';\n echo '&lt;p&gt;' . date_i18n('d F Y', strtotime($recent['post_date'])) .'&lt;/p&gt; ';\n echo get_the_category_list( ', ', '', $recent[\"ID\"] );\n }\n wp_reset_query();\n?&gt;\n</code></pre>\n" }, { "answer_id": 304511, "author": "Tahridabbas", "author_id": 144155, "author_profile": "https://wordpress.stackexchange.com/users/144155", "pm_score": 0, "selected": false, "text": "<p>i know This is the different code but works as you want hope so,you can try</p>\n\n<pre><code>&lt;?php\n $myposts = array( 'post_type' =&gt; 'post','posts_per_page' =&gt; 5); \n $all_post = new WP_Query($myposts);\n if ( $all_post-&gt;have_posts() ) :\n while ( $all_post-&gt;have_posts() ) :\n $all_post-&gt;the_post();\n\n echo get_the_title();\n echo '&lt;p&gt;' . 'Category Name:' . get_the_category_list($post-&gt;ID ) . '&lt;/p&gt;';\n endwhile;\n endif;\n wp_reset_postdata();\n?&gt;\n</code></pre>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274589", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I have a code for display recent posts: `<?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </h2> '; echo '<p>' . date_i18n('d F Y', strtotime($recent['post_date'])) .'</p> '; // what code here? } wp_reset_query(); ?>` now I want to display category name and link also. What kind of code should I use in here? I try some but without effect... Thx :)
You can use [`get_the_category_list()`](https://codex.wordpress.org/Function_Reference/get_the_category_list) to output a comma-separated list of links to categories: ``` <?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </h2> '; echo '<p>' . date_i18n('d F Y', strtotime($recent['post_date'])) .'</p> '; echo get_the_category_list( ', ', '', $recent["ID"] ); } wp_reset_query(); ?> ```
274,592
<p>I am trying to create some kind of repeated fields and for that, I want to create a new wp editor with some unique ID. </p> <p>So my question is there any way to create <code>wp_editor</code> using any js? same as we get using <code>&lt;?php wp_editor() ?&gt;</code> WordPress function.</p> <p>I have tried using </p> <pre><code>tinyMCE .init( { mode : "exact" , elements : "accordion_icon_description_"+response.success.item_count }); </code></pre> <p>but it prints very basic editor which is I think not same as of WordPress post content field editor</p>
[ { "answer_id": 274608, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 4, "selected": true, "text": "<p>Thanks to <a href=\"https://wordpress.stackexchange.com/questions/274592/how-to-create-wp-editor-using-javascript#comment407500_274592\">Jacob Peattie's comment</a> I can answer this using JS only. Actually we did something similar, but prior 4.8 and it wasn't this easy, so we did use <code>wp_editor()</code> in the end. But now, you can do so <a href=\"https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/\" rel=\"noreferrer\">using <code>wp.editor</code> object in JavaScript</a>. There are 3 main functions</p>\n\n<ol>\n<li><code>wp.editor.initialize = function( id, settings ) {</code></li>\n</ol>\n\n<p>Where <code>id</code> is </p>\n\n<blockquote>\n <p>The HTML id of the textarea that is used for the editor.\n Has to be jQuery compliant. No brackets, special chars, etc.</p>\n</blockquote>\n\n<p>and <code>settings</code> is either an object</p>\n\n<pre><code>{\n tinymce: {\n // tinymce settings\n },\n quicktags: {\n buttons: '..'\n }\n}\n</code></pre>\n\n<p>with these <a href=\"https://www.tinymce.com/docs/configure/integration-and-setup/\" rel=\"noreferrer\">TinyMCE settings</a>. Instead of any of the 3 objects (<code>settings</code> itself, <code>tinymce</code> or <code>quicktags</code>) you can use <code>true</code> to use the defaults.</p>\n\n<ol start=\"2\">\n<li><code>wp.editor.remove = function( id ) {</code></li>\n</ol>\n\n<p>Is quite self-explanatory. Remove any editor instance that was created via <code>wp.editor.initialize</code>.</p>\n\n<ol start=\"3\">\n<li><code>wp.editor.getContent = function( id ) {</code></li>\n</ol>\n\n<p>Well, get the content of any editor created via <code>wp.editor.initialize</code>.</p>\n\n<hr>\n\n<p>Usage could look like so</p>\n\n<pre><code>var countEditors = 0;\n$(document).on('click', 'button#addEditor', function() {\n var editorId = 'editor-' + countEditors;\n // add editor in HTML as &lt;textarea&gt; with id editorId\n // give it class wp-editor\n wp.editor.initialize(editorId, true);\n countEditors++;\n});\n$(document).on('click', 'button.removeEditor', function() {\n // assuming editor is under the same parent\n var editorId = $(this).parent().find('.wp-editor');\n wp.editor.remove(editorId);\n});\n</code></pre>\n\n<p>As the content will be automatically posted, it is not needed in this example. But you could always retrieve it via <code>wp.editor.getContent( editorId )</code></p>\n" }, { "answer_id": 280520, "author": "Antonio Novak", "author_id": 128215, "author_profile": "https://wordpress.stackexchange.com/users/128215", "pm_score": 2, "selected": false, "text": "<p>You need to use <code>wp_enqueue_editor();</code> first to output the editor scripts, stylesheets, and default settings. You can find this documented here <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_editor/\" rel=\"nofollow noreferrer\">wp_enqueue_editor()</a></p>\n\n<p>You need to remove true from function like so: <code>wp.editor.initialize(editorId);</code></p>\n" }, { "answer_id": 354974, "author": "Bjorn", "author_id": 83707, "author_profile": "https://wordpress.stackexchange.com/users/83707", "pm_score": 3, "selected": false, "text": "<p><strong>WP 5.3.2</strong></p>\n\n<p>Currently building a plugin with Ajax page loading, needed to get data from multiple WP editors that are dynamicly loaded.</p>\n\n<blockquote>\n <p>NOTE: Below example is for the wp-admin area, if you want this for the\n front-end you may need to extend.</p>\n</blockquote>\n\n<p>1.\nMake sure editor scripts are loaded with:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'load_admin_scripts');\nfunction load_admin_scripts() {\n // Do NOT load it on every admin page, create some logic to only load on your pages\n wp_enqueue_editor();\n}\n</code></pre>\n\n<p>2.\nGet editor textarea with Ajax (PHP):</p>\n\n<pre><code>function your_ajax_get_editor_callback() {\n // Note: every editor needs its own unique name and id\n return '&lt;textarea name=\"my-wp-editor\" id=\"my-wp-editor\" rows=\"12\" class=\"myprefix-wpeditor\"&gt;The value from database here :-)&lt;/textarea&gt;';\n}\n</code></pre>\n\n<p>3.\nUse Ajax JS script to load and remove the WP editors on Ajax success callback.</p>\n\n<blockquote>\n <p>I'm still playing around with all the available tinymce plugins, see\n TinyMCE docs and note that WP has renamed some of them. Check\n <code>wp-includes/js/tinymce/plugins</code>. In the example below I've added\n <code>fullscreen</code>, a handy plugin that's default off.</p>\n</blockquote>\n\n<pre><code>var active_editors = [];\n\nfunction ajax_succes_callback() {\n remove_active_editors();\n init_editors();\n}\n\nfunction remove_active_editors() {\n $.each( active_editors, function( i, editor_id ) {\n wp.editor.remove(editor_id);\n }\n active_editors = [];\n}\n\nfunction init_editors() {\n\n $.each( $('.myprefix-wpeditor'), function( i, editor ) {\n\n var editor_id = $(editor).attr('id');\n wp.editor.initialize(\n editor_id,\n {\n tinymce: {\n wpautop: true,\n plugins : 'charmap colorpicker compat3x directionality fullscreen hr image lists media paste tabfocus textcolor wordpress wpautoresize wpdialogs wpeditimage wpemoji wpgallery wplink wptextpattern wpview',\n toolbar1: 'bold italic underline strikethrough | bullist numlist | blockquote hr wp_more | alignleft aligncenter alignright | link unlink | fullscreen | wp_adv',\n toolbar2: 'formatselect alignjustify forecolor | pastetext removeformat charmap | outdent indent | undo redo | wp_help'\n },\n quicktags: true,\n mediaButtons: true,\n }\n );\n\n // Save id for removal later on\n active_editors.push(editor_id);\n\n });\n\n}\n</code></pre>\n\n<p>4.\nGet the content from each editor with:</p>\n\n<pre><code>function get_editor_content() {\n\n // NOTE: in my app the code below is inside a fields iteration (loop)\n\n var editor_id = $(field).attr('id');\n\n var mce_editor = tinymce.get(editor_id);\n if(mce_editor) {\n val = wp.editor.getContent(editor_id); // Visual tab is active\n } else {\n val = $('#'+editor_id).val(); // HTML tab is active\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Pointers:</strong></p>\n\n<ul>\n<li>Use <code>wp.editor.initialize(editor_id_here)</code> on a clean <code>&lt;textarea&gt;</code>, do not use <code>wp_editor()</code> for html output.</li>\n<li>Make sure you remove the editor with <code>wp.editor.remove(editor_id)</code> if its no longer present in the dom. If you do not do this, the editor init will fail when you load the editor (dynamicly) for a second time.</li>\n<li>Getting the editor content is different for each tab (Visual / HTML)</li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>NOTE: The above code samples are not fully tested and may contain some\n errors. I have it fully working in my app. It's purely to get\n you going.</p>\n</blockquote>\n" }, { "answer_id": 404568, "author": "John Dorner", "author_id": 20453, "author_profile": "https://wordpress.stackexchange.com/users/20453", "pm_score": 0, "selected": false, "text": "<pre><code>tinymce.execCommand( 'mceAddEditor', true, element.id );\n</code></pre>\n<p>did the trick for me.\nThanks to Goran Jakovljevic's answer on: <a href=\"https://wordpress.stackexchange.com/questions/106639/how-to-load-wp-editor-via-ajax\">How to load wp_editor via AJAX</a></p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114894/" ]
I am trying to create some kind of repeated fields and for that, I want to create a new wp editor with some unique ID. So my question is there any way to create `wp_editor` using any js? same as we get using `<?php wp_editor() ?>` WordPress function. I have tried using ``` tinyMCE .init( { mode : "exact" , elements : "accordion_icon_description_"+response.success.item_count }); ``` but it prints very basic editor which is I think not same as of WordPress post content field editor
Thanks to [Jacob Peattie's comment](https://wordpress.stackexchange.com/questions/274592/how-to-create-wp-editor-using-javascript#comment407500_274592) I can answer this using JS only. Actually we did something similar, but prior 4.8 and it wasn't this easy, so we did use `wp_editor()` in the end. But now, you can do so [using `wp.editor` object in JavaScript](https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/). There are 3 main functions 1. `wp.editor.initialize = function( id, settings ) {` Where `id` is > > The HTML id of the textarea that is used for the editor. > Has to be jQuery compliant. No brackets, special chars, etc. > > > and `settings` is either an object ``` { tinymce: { // tinymce settings }, quicktags: { buttons: '..' } } ``` with these [TinyMCE settings](https://www.tinymce.com/docs/configure/integration-and-setup/). Instead of any of the 3 objects (`settings` itself, `tinymce` or `quicktags`) you can use `true` to use the defaults. 2. `wp.editor.remove = function( id ) {` Is quite self-explanatory. Remove any editor instance that was created via `wp.editor.initialize`. 3. `wp.editor.getContent = function( id ) {` Well, get the content of any editor created via `wp.editor.initialize`. --- Usage could look like so ``` var countEditors = 0; $(document).on('click', 'button#addEditor', function() { var editorId = 'editor-' + countEditors; // add editor in HTML as <textarea> with id editorId // give it class wp-editor wp.editor.initialize(editorId, true); countEditors++; }); $(document).on('click', 'button.removeEditor', function() { // assuming editor is under the same parent var editorId = $(this).parent().find('.wp-editor'); wp.editor.remove(editorId); }); ``` As the content will be automatically posted, it is not needed in this example. But you could always retrieve it via `wp.editor.getContent( editorId )`
274,594
<p>i am getting various casino links on my site, i have searched everywhere in the files in my database, but i can't locate the issue, these links come and go they mostly appear in the header and the footer. After clicking on the link they linked to:</p> <pre><code>http://my/sitehollywood-casino-columbus-jobs/ </code></pre> <p>I have attached a screenshot. Your help is most appreciated. <a href="https://i.stack.imgur.com/R3MiA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R3MiA.png" alt="enter image description here"></a></p>
[ { "answer_id": 274602, "author": "Tony Cecala", "author_id": 124435, "author_profile": "https://wordpress.stackexchange.com/users/124435", "pm_score": 1, "selected": false, "text": "<p>Your site is almost definitely compromised. Doing your own cleanup may not be worth the time and effort because reinfection is likely if you miss a single infected file. \nAt this point I recommend to my clients that they get professional help. You may be able to get more details from a site scan by Sucuri. They have a free remote scan for virus infection.\n<a href=\"https://sitecheck.sucuri.net/\" rel=\"nofollow noreferrer\">Site scan by Sucuri</a></p>\n" }, { "answer_id": 274613, "author": "xvilo", "author_id": 104427, "author_profile": "https://wordpress.stackexchange.com/users/104427", "pm_score": 0, "selected": false, "text": "<p>Either rebuild your WordPress site from scratch. Ditch plugins that aren't updated for quite a while and don't paste and copy any content without proper inspection and sanitization.</p>\n\n<p>Or; <strong>ask a professional</strong> for help. who will probably rebuild the most part of your site from scratch! </p>\n" }, { "answer_id": 274625, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>If you want to fix it yourself, I'd do this:</p>\n\n<p>change the database password (ask the googles for help on this process)</p>\n\n<ul>\n<li><p>change your FTP passwords</p></li>\n<li><p>change your email passwords</p></li>\n<li><p>change your hosting passwords</p></li>\n<li><p>use strong passwords throughout</p></li>\n<li><p>use the Dashboard, Update to reinstall WP 4.8</p></li>\n<li><p>also update any plugins or themes noted there</p></li>\n<li><p>check the .htaccess file for changes (make a new one)</p></li>\n<li><p>reinstall all themes (download files from theme home and upload to the proper folder via FTP or cPanel)</p></li>\n<li><p>do the same for all plugins</p></li>\n<li><p>remove/delete any plugins/themes you don't need or use</p></li>\n<li><p>look for any posts/pages you didn't create; delete them </p></li>\n</ul>\n\n<p>Long-term, keep everything updated. This is a bit of work, but can be done with some knowledge (and you can also ask the googles how to do most things). If you aren't comfortable doing all that, then find a consultant that will help you. It will cost, as the whole process is time-consuming.</p>\n\n<p>Another option is to start from scratch - kill the old site completely (delete database and files) and reinstall everything. But that's not usually possible with most established sites.</p>\n\n<p>This hack/attack can be recovered from...I've done it before. It just takes a bit of time and knowledge to do it. If you have content that must be saved, it will be a bit more complex, but still doable.</p>\n\n<p>Good luck!</p>\n\n<p><strong>Added</strong></p>\n\n<p>And since you have a WooCommerce site, go through each product listing and remove anything that doesn't belong (could be some code inserted in a bogus product). </p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274594", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114702/" ]
i am getting various casino links on my site, i have searched everywhere in the files in my database, but i can't locate the issue, these links come and go they mostly appear in the header and the footer. After clicking on the link they linked to: ``` http://my/sitehollywood-casino-columbus-jobs/ ``` I have attached a screenshot. Your help is most appreciated. [![enter image description here](https://i.stack.imgur.com/R3MiA.png)](https://i.stack.imgur.com/R3MiA.png)
Your site is almost definitely compromised. Doing your own cleanup may not be worth the time and effort because reinfection is likely if you miss a single infected file. At this point I recommend to my clients that they get professional help. You may be able to get more details from a site scan by Sucuri. They have a free remote scan for virus infection. [Site scan by Sucuri](https://sitecheck.sucuri.net/)
274,624
<p>With a plugin I'm trying to develop, I'm trying to place some content on the front-page of the website after the header.</p> <p>In my plugin PHP file I have this (I've cut the html content out to save space):</p> <pre><code>add_action( '__after_header' , 'add_promotional_text', 4 ); function add_promotional_text() { // If we're on the home page, do something if ( ! is_admin() ) { if ( is_front_page() &amp;&amp; is_home() ){ return; //HTML goes here } } } do_action ( '__after_header' ); </code></pre> <p>This almost does what I want it to do. The content is not showing up in the admin area... and it does show up on the front-page like it is supposed to... however, it is also showing up on every page or post, which is not supposed to happen.</p> <p>It would be desirable for it to only show up on the front-page, and not on any other front-end facing pages.</p> <p>I am not sure how to do that.</p> <p>EDIT: </p> <p>I have simplified the plugin code to just this:</p> <pre><code>if ( is_front_page() &amp;&amp; is_home() ){ echo "&lt;script&gt;console.log( 'Debug Objects: is_front_page() &amp;&amp; Home()' );&lt;/script&gt;"; } else { echo "&lt;script&gt;console.log( 'Debug Objects: ! is_front_page() &amp;&amp; Home()' );&lt;/script&gt;"; } </code></pre> <p>And no matter how things are set in Settings > Reading, this if condition is never true. It is always false no matter where I navigate to in the site whether it is the front end or admin area.</p> <p><strong>Settings > Reading:</strong> <a href="https://i.stack.imgur.com/cWQql.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cWQql.png" alt="enter image description here"></a></p> <p><strong>Front Page with console output:</strong> <a href="https://i.stack.imgur.com/22xAd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/22xAd.png" alt="enter image description here"></a></p>
[ { "answer_id": 274629, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>This code appears wrong. Your version was doing a return if the front page or home was true. Change that part to this:</p>\n\n<pre><code>if ( is_front_page() &amp;&amp; is_home() ){\n // output the content because frontpage/home is true\n } else\n {\n // output content for any not frontpage/home\n }\n</code></pre>\n\n<p>Add whatever code needed for each condition</p>\n" }, { "answer_id": 274867, "author": "Livi17", "author_id": 15447, "author_profile": "https://wordpress.stackexchange.com/users/15447", "pm_score": 2, "selected": true, "text": "<p>After turning on WP_DEBUG, </p>\n\n<pre><code>define('WP_DEBUG', true);\n</code></pre>\n\n<p>I was receiving the error: <strong>Conditional query tags do not work before the query is run. Before then, they always return false.</strong></p>\n\n<p>After googling that error, I found a solution that works:</p>\n\n<pre><code>add_action( 'template_redirect', 'check_for_frontpage' );\n\nfunction check_for_frontpage() {\n if ( is_front_page() || is_home() ) {\n echo \"&lt;script&gt;console.log( 'Debug Objects: is_front_page() &amp;&amp; Home()' );&lt;/script&gt;\";\n } else {\n echo \"&lt;script&gt;console.log( 'Debug Objects: ! is_front_page() &amp;&amp; Home()' );&lt;/script&gt;\";\n }\n}\n</code></pre>\n" }, { "answer_id": 274868, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>So in the <a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"nofollow noreferrer\">docs</a> say that the <code>is_home</code> and <code>is_front_page</code>, can return diferent values depending on the page. Here are some examples:</p>\n\n<blockquote>\n <ul>\n <li><p>If <code>'posts' == get_option( 'show_on_front' )</code>:</p>\n \n <ul>\n <li><p>On the site front page:</p>\n \n <ul>\n <li><code>is_front_page()</code> will return true</li>\n <li><code>is_home()</code> will return true</li>\n </ul></li>\n <li><p>If assigned, WordPress ignores the pages assigned to display the site front page or the blog posts index</p></li>\n </ul></li>\n <li><p>If <code>'page' == get_option( 'show_on_front' )</code>: </p>\n \n <ul>\n <li><p>On the page assigned to display the site front page:</p>\n \n <ul>\n <li><code>is_front_page()</code> will return true</li>\n <li><code>is_home()</code> will return false</li>\n </ul></li>\n <li><p>On the page assigned to display the blog posts index:</p>\n \n <ul>\n <li><code>is_front_page()</code> will return false</li>\n <li><code>is_home()</code> will return true</li>\n </ul></li>\n </ul></li>\n </ul>\n</blockquote>\n\n<p>So if you set a static page to apper on front of the site <code>home_url</code> will return false. If you change you code to this: </p>\n\n<pre><code>if ( is_front_page() &amp;&amp; is_page('home') ){\n // output the content because frontpage/home is true\n} \nelse {\n // output content for any not frontpage/home\n}\n</code></pre>\n\n<p>Where <code>'home'</code> is the slug of the page where you marked to show on front, will work.</p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15447/" ]
With a plugin I'm trying to develop, I'm trying to place some content on the front-page of the website after the header. In my plugin PHP file I have this (I've cut the html content out to save space): ``` add_action( '__after_header' , 'add_promotional_text', 4 ); function add_promotional_text() { // If we're on the home page, do something if ( ! is_admin() ) { if ( is_front_page() && is_home() ){ return; //HTML goes here } } } do_action ( '__after_header' ); ``` This almost does what I want it to do. The content is not showing up in the admin area... and it does show up on the front-page like it is supposed to... however, it is also showing up on every page or post, which is not supposed to happen. It would be desirable for it to only show up on the front-page, and not on any other front-end facing pages. I am not sure how to do that. EDIT: I have simplified the plugin code to just this: ``` if ( is_front_page() && is_home() ){ echo "<script>console.log( 'Debug Objects: is_front_page() && Home()' );</script>"; } else { echo "<script>console.log( 'Debug Objects: ! is_front_page() && Home()' );</script>"; } ``` And no matter how things are set in Settings > Reading, this if condition is never true. It is always false no matter where I navigate to in the site whether it is the front end or admin area. **Settings > Reading:** [![enter image description here](https://i.stack.imgur.com/cWQql.png)](https://i.stack.imgur.com/cWQql.png) **Front Page with console output:** [![enter image description here](https://i.stack.imgur.com/22xAd.png)](https://i.stack.imgur.com/22xAd.png)
After turning on WP\_DEBUG, ``` define('WP_DEBUG', true); ``` I was receiving the error: **Conditional query tags do not work before the query is run. Before then, they always return false.** After googling that error, I found a solution that works: ``` add_action( 'template_redirect', 'check_for_frontpage' ); function check_for_frontpage() { if ( is_front_page() || is_home() ) { echo "<script>console.log( 'Debug Objects: is_front_page() && Home()' );</script>"; } else { echo "<script>console.log( 'Debug Objects: ! is_front_page() && Home()' );</script>"; } } ```
274,650
<p>In WordPress, I use a function in functions.php to only not show certain posts(by category) if a user is not signed in:</p> <pre><code> function my_filter( $content ) { $categories = array( 'news', 'opinions', 'sports', 'other', ); if ( in_category( $categories ) ) { if ( is_logged_in() ) { return $content; } else { $content = '&lt;p&gt;Sorry, this post is only available to members&lt;/p&gt; &lt;a href="gateblogs.com/login"&gt; Login &lt;/a&gt;'; return $content; } } else { return $content; } } add_filter( 'the_content', 'my_filter' ); </code></pre> <p>I use a plugin(not important to my question), but basically, I can use something like <code>https://gateblogs.com/login?redirect_to=https%3A%2F%2Fgateblogs.com%2Ftechnology%2Flinux-tutorials%2Fsending-mail-from-server</code> to redirect to a page after a successful login. How can I get a post's URL and apply it into the sign up link.</p> <p>Note: The function is originally from <a href="https://wordpress.stackexchange.com/questions/274296/how-can-i-only-show-certain-posts">this question</a>.</p>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjunction with <code>is_single()</code>:</p>\n\n<pre><code>add_filter( 'the_content', 'my_filter' );\n\nfunction my_filter( $content ) {\n\n // Check if we're inside the main loop in a single post page.\n if ( is_single() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() ) {\n return $content . get_the_permalink();\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 274652, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>I figured out how to do it with the <code>get_the_permalink()</code> function:</p>\n\n<pre><code>/* Protect Member Only Posts*/\nfunction post_filter( $content ) {\n\n $categories = array(\n 'coding',\n 'python',\n 'linux-tutorials',\n 'swift',\n 'premium',\n );\n if ( in_category( $categories ) ) {\n if ( is_user_logged_in() ) {\n return $content;\n } else {\n $link = get_the_permalink();\n $link = str_replace(':', '%3A', $link);\n $link = str_replace('/', '%2F', $link);\n $content = \"&lt;p&gt;Sorry, this post is only available to members. &lt;a href=\\\"gateblogs.com/login?redirect_to=$link\\\"&gt;Sign in/Register&lt;/a&gt;&lt;/p&gt;\";\n return $content;\n }\n } else {\n return $content;\n }\n}\nadd_filter( 'the_content', 'post_filter' );\n</code></pre>\n\n<p>Please note than the <code>str_replace</code> is because I has to change the link for the plugin to work.</p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
In WordPress, I use a function in functions.php to only not show certain posts(by category) if a user is not signed in: ``` function my_filter( $content ) { $categories = array( 'news', 'opinions', 'sports', 'other', ); if ( in_category( $categories ) ) { if ( is_logged_in() ) { return $content; } else { $content = '<p>Sorry, this post is only available to members</p> <a href="gateblogs.com/login"> Login </a>'; return $content; } } else { return $content; } } add_filter( 'the_content', 'my_filter' ); ``` I use a plugin(not important to my question), but basically, I can use something like `https://gateblogs.com/login?redirect_to=https%3A%2F%2Fgateblogs.com%2Ftechnology%2Flinux-tutorials%2Fsending-mail-from-server` to redirect to a page after a successful login. How can I get a post's URL and apply it into the sign up link. Note: The function is originally from [this question](https://wordpress.stackexchange.com/questions/274296/how-can-i-only-show-certain-posts).
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,659
<p>I apologize for asking such a simple question, but I am having a world of struggle in trying to convert the following echo statement to HTML with php tags inside of it. I am trying to get my custom metabox to work correctly, but it will not save my data unless I use the following format as an echo string (very frustrating).</p> <p>Thanks for any advice</p> <pre><code>echo '&lt;p&gt; &lt;label&gt; &lt;select name="horizon_sort_listb" id="horizon_sort_listb"&gt; &lt;option value="0" ' .selected($horizon_featured,'normal',false) .'&gt;Descending&lt;/option&gt; &lt;option value="special" ' .selected($horizon_featured, 'special',false) .'&gt;Ascending&lt;/option&gt; &lt;/select&gt;&lt;strong&gt;Sort Order B&lt;/strong&gt;' .'&lt;/label&gt; &lt;/p&gt;'; ?&gt; </code></pre>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjunction with <code>is_single()</code>:</p>\n\n<pre><code>add_filter( 'the_content', 'my_filter' );\n\nfunction my_filter( $content ) {\n\n // Check if we're inside the main loop in a single post page.\n if ( is_single() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() ) {\n return $content . get_the_permalink();\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 274652, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>I figured out how to do it with the <code>get_the_permalink()</code> function:</p>\n\n<pre><code>/* Protect Member Only Posts*/\nfunction post_filter( $content ) {\n\n $categories = array(\n 'coding',\n 'python',\n 'linux-tutorials',\n 'swift',\n 'premium',\n );\n if ( in_category( $categories ) ) {\n if ( is_user_logged_in() ) {\n return $content;\n } else {\n $link = get_the_permalink();\n $link = str_replace(':', '%3A', $link);\n $link = str_replace('/', '%2F', $link);\n $content = \"&lt;p&gt;Sorry, this post is only available to members. &lt;a href=\\\"gateblogs.com/login?redirect_to=$link\\\"&gt;Sign in/Register&lt;/a&gt;&lt;/p&gt;\";\n return $content;\n }\n } else {\n return $content;\n }\n}\nadd_filter( 'the_content', 'post_filter' );\n</code></pre>\n\n<p>Please note than the <code>str_replace</code> is because I has to change the link for the plugin to work.</p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274659", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
I apologize for asking such a simple question, but I am having a world of struggle in trying to convert the following echo statement to HTML with php tags inside of it. I am trying to get my custom metabox to work correctly, but it will not save my data unless I use the following format as an echo string (very frustrating). Thanks for any advice ``` echo '<p> <label> <select name="horizon_sort_listb" id="horizon_sort_listb"> <option value="0" ' .selected($horizon_featured,'normal',false) .'>Descending</option> <option value="special" ' .selected($horizon_featured, 'special',false) .'>Ascending</option> </select><strong>Sort Order B</strong>' .'</label> </p>'; ?> ```
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,663
<p>I'm writing a query that switches to the main blog of a MU site using switch_to_blog(). All is well except i'm attempting to write a wp_query that includes a variable needed from the previous blog. All the content being pulled from the main blog is stored in a CPT with a taxonomy that corresponds to the various sub-blog names. I'm attempting to store bloginfo('name'); from my previous blog, and pull it into the query after switch_to_blog, but for obvious reasons, no luck (it gets the current bloginfo, not the previous.) Is there any way either to save the the previous bloginfo into a global of some sort, or to switch back to the previous blog just to get that variable mid-query? </p> <p>See my query below for better illustration:</p> <pre><code>$location = bloginfo('name'); switch_to_blog( 1 ); $the_query = new WP_Query( array( 'post_type' =&gt; 'staff', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'location', // name of tax 'field' =&gt; 'slug', 'terms' =&gt; $location, // this doesn't work, returns nothing ), ), ) ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php endwhile; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php restore_current_blog(); ?&gt; </code></pre>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjunction with <code>is_single()</code>:</p>\n\n<pre><code>add_filter( 'the_content', 'my_filter' );\n\nfunction my_filter( $content ) {\n\n // Check if we're inside the main loop in a single post page.\n if ( is_single() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() ) {\n return $content . get_the_permalink();\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 274652, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>I figured out how to do it with the <code>get_the_permalink()</code> function:</p>\n\n<pre><code>/* Protect Member Only Posts*/\nfunction post_filter( $content ) {\n\n $categories = array(\n 'coding',\n 'python',\n 'linux-tutorials',\n 'swift',\n 'premium',\n );\n if ( in_category( $categories ) ) {\n if ( is_user_logged_in() ) {\n return $content;\n } else {\n $link = get_the_permalink();\n $link = str_replace(':', '%3A', $link);\n $link = str_replace('/', '%2F', $link);\n $content = \"&lt;p&gt;Sorry, this post is only available to members. &lt;a href=\\\"gateblogs.com/login?redirect_to=$link\\\"&gt;Sign in/Register&lt;/a&gt;&lt;/p&gt;\";\n return $content;\n }\n } else {\n return $content;\n }\n}\nadd_filter( 'the_content', 'post_filter' );\n</code></pre>\n\n<p>Please note than the <code>str_replace</code> is because I has to change the link for the plugin to work.</p>\n" } ]
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16111/" ]
I'm writing a query that switches to the main blog of a MU site using switch\_to\_blog(). All is well except i'm attempting to write a wp\_query that includes a variable needed from the previous blog. All the content being pulled from the main blog is stored in a CPT with a taxonomy that corresponds to the various sub-blog names. I'm attempting to store bloginfo('name'); from my previous blog, and pull it into the query after switch\_to\_blog, but for obvious reasons, no luck (it gets the current bloginfo, not the previous.) Is there any way either to save the the previous bloginfo into a global of some sort, or to switch back to the previous blog just to get that variable mid-query? See my query below for better illustration: ``` $location = bloginfo('name'); switch_to_blog( 1 ); $the_query = new WP_Query( array( 'post_type' => 'staff', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'location', // name of tax 'field' => 'slug', 'terms' => $location, // this doesn't work, returns nothing ), ), ) ); ?> <?php if ( $the_query->have_posts() ) : ?> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> <?php restore_current_blog(); ?> ```
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,668
<p>I have a handful of products in my WooCommerce Store set to <code>Catalog &amp; Search</code> and a bunch more just set to a visibility of just <code>Search</code>.</p> <p>I put a lot of work into making sure my Catalog was nice and clean, but now I need to do some additional work on them and am trying to retrieve the IDs of products that are ONLY in my Catalog and not just search.</p> <p>I've tried a few things, but something is amiss somewhere.</p> <p>What am I missing?</p> <pre><code>$params = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'product', 'orderby' =&gt; 'menu-order', 'order' =&gt; 'asc', 'fields' =&gt; 'ids', 'meta_query' =&gt; array( array( 'taxonomy' =&gt; 'product_visibility', 'value' =&gt; 'exclude-from-catalog', 'compare' =&gt; '!=') )); $wc_query = new WP_Query($params); $ids = $wc_query-&gt;posts; echo '&lt;pre&gt;'; print_r($ids); echo '&lt;/pre&gt;'; </code></pre> <p>With this Query it's still returning all Product IDs.</p> <p>I'm assuming there must be something wrong with my <code>meta_query</code> argument. What I was going for was to look for the <code>product_visibility</code> <code>taxonomy</code> and exclude (<code>!=</code>) those that have the value <code>exclude-from-catalog</code>.</p> <p>Anyone know where I'm going wrong with this?</p>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjunction with <code>is_single()</code>:</p>\n\n<pre><code>add_filter( 'the_content', 'my_filter' );\n\nfunction my_filter( $content ) {\n\n // Check if we're inside the main loop in a single post page.\n if ( is_single() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() ) {\n return $content . get_the_permalink();\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 274652, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>I figured out how to do it with the <code>get_the_permalink()</code> function:</p>\n\n<pre><code>/* Protect Member Only Posts*/\nfunction post_filter( $content ) {\n\n $categories = array(\n 'coding',\n 'python',\n 'linux-tutorials',\n 'swift',\n 'premium',\n );\n if ( in_category( $categories ) ) {\n if ( is_user_logged_in() ) {\n return $content;\n } else {\n $link = get_the_permalink();\n $link = str_replace(':', '%3A', $link);\n $link = str_replace('/', '%2F', $link);\n $content = \"&lt;p&gt;Sorry, this post is only available to members. &lt;a href=\\\"gateblogs.com/login?redirect_to=$link\\\"&gt;Sign in/Register&lt;/a&gt;&lt;/p&gt;\";\n return $content;\n }\n } else {\n return $content;\n }\n}\nadd_filter( 'the_content', 'post_filter' );\n</code></pre>\n\n<p>Please note than the <code>str_replace</code> is because I has to change the link for the plugin to work.</p>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274668", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121874/" ]
I have a handful of products in my WooCommerce Store set to `Catalog & Search` and a bunch more just set to a visibility of just `Search`. I put a lot of work into making sure my Catalog was nice and clean, but now I need to do some additional work on them and am trying to retrieve the IDs of products that are ONLY in my Catalog and not just search. I've tried a few things, but something is amiss somewhere. What am I missing? ``` $params = array( 'posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'menu-order', 'order' => 'asc', 'fields' => 'ids', 'meta_query' => array( array( 'taxonomy' => 'product_visibility', 'value' => 'exclude-from-catalog', 'compare' => '!=') )); $wc_query = new WP_Query($params); $ids = $wc_query->posts; echo '<pre>'; print_r($ids); echo '</pre>'; ``` With this Query it's still returning all Product IDs. I'm assuming there must be something wrong with my `meta_query` argument. What I was going for was to look for the `product_visibility` `taxonomy` and exclude (`!=`) those that have the value `exclude-from-catalog`. Anyone know where I'm going wrong with this?
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,676
<p>I created a search for my site using attachments. Each attachment is in category "Pictures", so my search form looks like:</p> <pre><code>&lt;form method="get" id="searchform" action="&lt;?php bloginfo('url'); ?&gt;"&gt; &lt;input type="text" name="s" id="s" value="Search..." onfocus="if (this.value=='Search...') this.value='';" onblur="if (this.value=='') this.value='Search...';" /&gt; &lt;?php $parent = get_cat_ID("Pictures"); ?&gt; &lt;input type="hidden" name="cat" value="&lt;?php echo $parent; ?&gt;" /&gt; &lt;input type="submit" id="searchsubmit" value="" /&gt; &lt;/form&gt; </code></pre> <p>My search results page <code>search.php</code> returns those results through a <code>get_posts</code>query. The problem I am having is with the pagination. I have been able to limit the number of posts on the page and even return the pagination, but when I click on the link for the pagination, the page does not display. I am thinking because these are attachments the pages are setup a little different, but I don't know what the url looks like. My current code looks like:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; '-1', 'category_name' =&gt; get_the_title() ); $images = get_posts($args); if (!empty($images)) { ?&gt; &lt;?php $limit = 5; $total = count($images); $pages = ceil($total / $limit); $result = ceil($total / $limit); $current = isset($_GET['paged']) ? $_GET['paged'] : 1; $next = $current &lt; $pages ? $current + 1 : null; $previous = $current &gt; 1 ? $current - 1 : null; $offset = ($current - 1) * $limit; $images = array_slice($images, $offset, $limit) ?&gt; &lt;h4&gt;&lt;span&gt;Search&lt;/span&gt; Results&lt;/h4&gt; &lt;ul class="category"&gt; &lt;?php foreach ($images as $image) { $title = $image-&gt;post_title; $description = $image-&gt;post_content; $attachment_link = get_attachment_link( $image-&gt;ID ); ?&gt; &lt;li&gt; &lt;div class="col1"&gt; &lt;a href="&lt;?php echo $attachment_link; ?&gt;"&gt;&lt;?php echo wp_get_attachment_image($image-&gt;ID, "medium"); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col2"&gt; &lt;h5&gt;&lt;?php echo $title; ?&gt;&lt;/h5&gt; &lt;p&gt;&lt;?php echo $description; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;?php echo "&lt;p&gt;(Page: ". $current . " of " . $result .")&lt;/p&gt;"; ?&gt; &lt;? if($previous): ?&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;?paged&lt;?= $previous ?&gt;"&gt;Previous&lt;/a&gt; &lt;? endif ?&gt; &lt;? if($next) : ?&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;?paged&lt;?= $next ?&gt;"&gt;Next&lt;/a&gt; &lt;? endif ?&gt; &lt;?php } ?&gt; </code></pre> <p>The paging was integrated from the code I found on: <a href="https://erikeldridge.wordpress.com/2009/01/11/simple-php-paging/" rel="nofollow noreferrer">https://erikeldridge.wordpress.com/2009/01/11/simple-php-paging/</a></p> <p>I'm so close, probably just a tweak here or there, can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjunction with <code>is_single()</code>:</p>\n\n<pre><code>add_filter( 'the_content', 'my_filter' );\n\nfunction my_filter( $content ) {\n\n // Check if we're inside the main loop in a single post page.\n if ( is_single() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() ) {\n return $content . get_the_permalink();\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 274652, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>I figured out how to do it with the <code>get_the_permalink()</code> function:</p>\n\n<pre><code>/* Protect Member Only Posts*/\nfunction post_filter( $content ) {\n\n $categories = array(\n 'coding',\n 'python',\n 'linux-tutorials',\n 'swift',\n 'premium',\n );\n if ( in_category( $categories ) ) {\n if ( is_user_logged_in() ) {\n return $content;\n } else {\n $link = get_the_permalink();\n $link = str_replace(':', '%3A', $link);\n $link = str_replace('/', '%2F', $link);\n $content = \"&lt;p&gt;Sorry, this post is only available to members. &lt;a href=\\\"gateblogs.com/login?redirect_to=$link\\\"&gt;Sign in/Register&lt;/a&gt;&lt;/p&gt;\";\n return $content;\n }\n } else {\n return $content;\n }\n}\nadd_filter( 'the_content', 'post_filter' );\n</code></pre>\n\n<p>Please note than the <code>str_replace</code> is because I has to change the link for the plugin to work.</p>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274676", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I created a search for my site using attachments. Each attachment is in category "Pictures", so my search form looks like: ``` <form method="get" id="searchform" action="<?php bloginfo('url'); ?>"> <input type="text" name="s" id="s" value="Search..." onfocus="if (this.value=='Search...') this.value='';" onblur="if (this.value=='') this.value='Search...';" /> <?php $parent = get_cat_ID("Pictures"); ?> <input type="hidden" name="cat" value="<?php echo $parent; ?>" /> <input type="submit" id="searchsubmit" value="" /> </form> ``` My search results page `search.php` returns those results through a `get_posts`query. The problem I am having is with the pagination. I have been able to limit the number of posts on the page and even return the pagination, but when I click on the link for the pagination, the page does not display. I am thinking because these are attachments the pages are setup a little different, but I don't know what the url looks like. My current code looks like: ``` <?php $args = array( 'post_type' => 'attachment', 'numberposts' => '-1', 'category_name' => get_the_title() ); $images = get_posts($args); if (!empty($images)) { ?> <?php $limit = 5; $total = count($images); $pages = ceil($total / $limit); $result = ceil($total / $limit); $current = isset($_GET['paged']) ? $_GET['paged'] : 1; $next = $current < $pages ? $current + 1 : null; $previous = $current > 1 ? $current - 1 : null; $offset = ($current - 1) * $limit; $images = array_slice($images, $offset, $limit) ?> <h4><span>Search</span> Results</h4> <ul class="category"> <?php foreach ($images as $image) { $title = $image->post_title; $description = $image->post_content; $attachment_link = get_attachment_link( $image->ID ); ?> <li> <div class="col1"> <a href="<?php echo $attachment_link; ?>"><?php echo wp_get_attachment_image($image->ID, "medium"); ?></a> </div> <div class="col2"> <h5><?php echo $title; ?></h5> <p><?php echo $description; ?></p> </div> </li> <?php } ?> </ul> <?php echo "<p>(Page: ". $current . " of " . $result .")</p>"; ?> <? if($previous): ?> <a href="<?php bloginfo('url'); ?>?paged<?= $previous ?>">Previous</a> <? endif ?> <? if($next) : ?> <a href="<?php bloginfo('url'); ?>?paged<?= $next ?>">Next</a> <? endif ?> <?php } ?> ``` The paging was integrated from the code I found on: <https://erikeldridge.wordpress.com/2009/01/11/simple-php-paging/> I'm so close, probably just a tweak here or there, can anyone point me in the right direction? Thanks, Josh
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,677
<p>I am trying to display a function using AJAX using a custom plugin. But doesn't seem to work.</p> <p>My Javascript</p> <pre><code>(function($) { $(document).on( 'click', 'a.mylink', function( event ) { $.ajax({ url: testing.ajax_url, data : { action : 'diplay_user_table' }, success : function( response ) { jQuery('#user_reponse').html( response ); } }) }) })(jQuery); </code></pre> <p>My PHP</p> <pre><code>add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); function ajax_test_enqueue_scripts() { wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true ); wp_localize_script( 'test', 'testing', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) )); } add_action('wp_ajax_my_action', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; } </code></pre> <p>When I click on link it just displays '0'. Any ideas?</p>
[ { "answer_id": 274680, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You're not hooking the function to wp_ajax correctly. You need to replace the <code>my_action</code> part with your action name that you're using the in AJAX request. In your case it's <code>display_user_table</code>. You also need to hook it on to <code>wp_ajax_nopriv</code> so that it works for logged out users. Here's your hook with those changes:</p>\n\n<pre><code>add_action('wp_ajax_diplay_user_table', 'diplay_user_table');\nadd_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table');\nfunction diplay_user_table() {\n echo \"function is loading in div\";\n wp_die();\n}\n</code></pre>\n" }, { "answer_id": 274688, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can use a faster and quicker method, to get rid of the annoying 0 that is chasing every AJAX request to the end. By using a REST API endpoint, you don't need to write different actions for logged-in and non-logged-in users.</p>\n\n<p>Here is a quick example:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'aido14', '/my_path/', array(\n 'methods' =&gt; 'GET', \n 'callback' =&gt; 'diplay_user_table' \n ) );\n});\n// Callback function\nfunction diplay_user_table() {\n $data['test1'] = \"function is loading in div\";\n}\nadd_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );\nfunction ajax_test_enqueue_scripts() {\n wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );\n wp_localize_script( 'test', 'testing', array(\n 'ajax_url' =&gt; site_url()\n ));\n}\n</code></pre>\n\n<p>And your JavaScript:</p>\n\n<pre><code>(function($) {\n $(document).on( 'click', 'a.mylink', function( event ) {\n $.ajax({\n url: testing.ajax_url + '/wp-json/aido14/my_path',\n data : { parameter-here : value-here \n },\n success : function( response.test1 ) {\n jQuery('#user_reponse').html( response );\n }\n });\n})\n})(jQuery);\n</code></pre>\n\n<p>Now, you get the same result by visiting <code>/wp-json/aido14/my_path</code>. A neat JSON response which you can use even in mobile apps.</p>\n\n<p>And, as you can see, you can pass several responses in a single request by storing them in an array. This will come in handy for example in contact and login forms.</p>\n" }, { "answer_id": 353961, "author": "user179352", "author_id": 179352, "author_profile": "https://wordpress.stackexchange.com/users/179352", "pm_score": 0, "selected": false, "text": "<p>Try running this code</p>\n\n<pre>\nadd_action('wp_ajax_diplay_user_table', 'diplay_user_table');\nadd_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table');\nfunction diplay_user_table() {\n ob_start();\n echo \"function is loading in div\";\n $data = ob_get_clean();\n echo $data;\n die();\n\n}\n</pre>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105139/" ]
I am trying to display a function using AJAX using a custom plugin. But doesn't seem to work. My Javascript ``` (function($) { $(document).on( 'click', 'a.mylink', function( event ) { $.ajax({ url: testing.ajax_url, data : { action : 'diplay_user_table' }, success : function( response ) { jQuery('#user_reponse').html( response ); } }) }) })(jQuery); ``` My PHP ``` add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); function ajax_test_enqueue_scripts() { wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true ); wp_localize_script( 'test', 'testing', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )); } add_action('wp_ajax_my_action', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; } ``` When I click on link it just displays '0'. Any ideas?
You're not hooking the function to wp\_ajax correctly. You need to replace the `my_action` part with your action name that you're using the in AJAX request. In your case it's `display_user_table`. You also need to hook it on to `wp_ajax_nopriv` so that it works for logged out users. Here's your hook with those changes: ``` add_action('wp_ajax_diplay_user_table', 'diplay_user_table'); add_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; wp_die(); } ```
274,683
<p>This is the bottom half of my child theme's functions.php.</p> <pre><code>function register_my_scripts(){ if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); </code></pre> <p>Why is it, when I have the following code in the same file (above it), then the style enqueues in the above code block (but below on my file) stop working, even though the 'if' block still runs (I tested with "echo 'something';" and the echo ran)?</p> <pre><code>function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } </code></pre> <p>But when i comment out the wp_enqueue_style in the same line, so the whole file looks like:</p> <pre><code>function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } add_action( 'init', 'register_my_menu'); function register_my_scripts(){ // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); </code></pre> <p>The enqueues in <code>register_my_scripts()</code> runs properly again. </p> <p>This is a conflict that I have never seen anywhere, and why the hell doesn't WordPress throw some kind of error. It's hellish to debug these things. </p> <p>Is there a strict version of WordPress I can get somewhere, like JavaScript's "use strict"? </p> <p>The fact that they never throw any errors is sickening. </p>
[ { "answer_id": 274680, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You're not hooking the function to wp_ajax correctly. You need to replace the <code>my_action</code> part with your action name that you're using the in AJAX request. In your case it's <code>display_user_table</code>. You also need to hook it on to <code>wp_ajax_nopriv</code> so that it works for logged out users. Here's your hook with those changes:</p>\n\n<pre><code>add_action('wp_ajax_diplay_user_table', 'diplay_user_table');\nadd_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table');\nfunction diplay_user_table() {\n echo \"function is loading in div\";\n wp_die();\n}\n</code></pre>\n" }, { "answer_id": 274688, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can use a faster and quicker method, to get rid of the annoying 0 that is chasing every AJAX request to the end. By using a REST API endpoint, you don't need to write different actions for logged-in and non-logged-in users.</p>\n\n<p>Here is a quick example:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'aido14', '/my_path/', array(\n 'methods' =&gt; 'GET', \n 'callback' =&gt; 'diplay_user_table' \n ) );\n});\n// Callback function\nfunction diplay_user_table() {\n $data['test1'] = \"function is loading in div\";\n}\nadd_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );\nfunction ajax_test_enqueue_scripts() {\n wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );\n wp_localize_script( 'test', 'testing', array(\n 'ajax_url' =&gt; site_url()\n ));\n}\n</code></pre>\n\n<p>And your JavaScript:</p>\n\n<pre><code>(function($) {\n $(document).on( 'click', 'a.mylink', function( event ) {\n $.ajax({\n url: testing.ajax_url + '/wp-json/aido14/my_path',\n data : { parameter-here : value-here \n },\n success : function( response.test1 ) {\n jQuery('#user_reponse').html( response );\n }\n });\n})\n})(jQuery);\n</code></pre>\n\n<p>Now, you get the same result by visiting <code>/wp-json/aido14/my_path</code>. A neat JSON response which you can use even in mobile apps.</p>\n\n<p>And, as you can see, you can pass several responses in a single request by storing them in an array. This will come in handy for example in contact and login forms.</p>\n" }, { "answer_id": 353961, "author": "user179352", "author_id": 179352, "author_profile": "https://wordpress.stackexchange.com/users/179352", "pm_score": 0, "selected": false, "text": "<p>Try running this code</p>\n\n<pre>\nadd_action('wp_ajax_diplay_user_table', 'diplay_user_table');\nadd_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table');\nfunction diplay_user_table() {\n ob_start();\n echo \"function is loading in div\";\n $data = ob_get_clean();\n echo $data;\n die();\n\n}\n</pre>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124596/" ]
This is the bottom half of my child theme's functions.php. ``` function register_my_scripts(){ if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); ``` Why is it, when I have the following code in the same file (above it), then the style enqueues in the above code block (but below on my file) stop working, even though the 'if' block still runs (I tested with "echo 'something';" and the echo ran)? ``` function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } ``` But when i comment out the wp\_enqueue\_style in the same line, so the whole file looks like: ``` function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } add_action( 'init', 'register_my_menu'); function register_my_scripts(){ // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); ``` The enqueues in `register_my_scripts()` runs properly again. This is a conflict that I have never seen anywhere, and why the hell doesn't WordPress throw some kind of error. It's hellish to debug these things. Is there a strict version of WordPress I can get somewhere, like JavaScript's "use strict"? The fact that they never throw any errors is sickening.
You're not hooking the function to wp\_ajax correctly. You need to replace the `my_action` part with your action name that you're using the in AJAX request. In your case it's `display_user_table`. You also need to hook it on to `wp_ajax_nopriv` so that it works for logged out users. Here's your hook with those changes: ``` add_action('wp_ajax_diplay_user_table', 'diplay_user_table'); add_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; wp_die(); } ```
274,696
<p>I want to change the registration form of WooCommerce a little bit. I'm fine with the normal form which comes from WooCommerce but I want to add the following fields and functions:</p> <p>If a person enters the email and the password and press register, the person should be redirected to another page where the person is forced to enter the address, phone number and the full name. But how can I do that? I already googled but found nothing... Further, only if the person has entered the details, the confirmtion mail should be send. All that should also be safed with a recaptcher at the end.</p> <p>Does anybody has an idea how I can solve that? Would it be possible to redirect the person after entering the email and passwords details to a page where the person is supposed to enter the shipping details and only if those are entered the confirmtion mail gets sended?</p> <p>Kind Regards and Thank You!</p>
[ { "answer_id": 275011, "author": "dbdesigns", "author_id": 119686, "author_profile": "https://wordpress.stackexchange.com/users/119686", "pm_score": 0, "selected": false, "text": "<p>I've been trying out the same code snippet from Cloudways as well. If you don't use the snippet in functions.php, but instead create a copy of the woocommerce file form-login.php in your child theme's folder/woocommerce/myaccount. Then the fields from the Couldways snippet can be used before the line containing:</p>\n\n<pre><code>&lt;?php do_action( 'woocommerce_after_checkout_billing_form', $checkout ); ?&gt;\n</code></pre>\n" }, { "answer_id": 300163, "author": "AJT", "author_id": 56986, "author_profile": "https://wordpress.stackexchange.com/users/56986", "pm_score": -1, "selected": false, "text": "<p>There's a plugin I've been using that lets you add the billing and/or shipping address fields right on the user registration form. It might do what you need, have a look here: <a href=\"https://wordpress.org/plugins/wc-afour/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wc-afour/</a></p>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123952/" ]
I want to change the registration form of WooCommerce a little bit. I'm fine with the normal form which comes from WooCommerce but I want to add the following fields and functions: If a person enters the email and the password and press register, the person should be redirected to another page where the person is forced to enter the address, phone number and the full name. But how can I do that? I already googled but found nothing... Further, only if the person has entered the details, the confirmtion mail should be send. All that should also be safed with a recaptcher at the end. Does anybody has an idea how I can solve that? Would it be possible to redirect the person after entering the email and passwords details to a page where the person is supposed to enter the shipping details and only if those are entered the confirmtion mail gets sended? Kind Regards and Thank You!
I've been trying out the same code snippet from Cloudways as well. If you don't use the snippet in functions.php, but instead create a copy of the woocommerce file form-login.php in your child theme's folder/woocommerce/myaccount. Then the fields from the Couldways snippet can be used before the line containing: ``` <?php do_action( 'woocommerce_after_checkout_billing_form', $checkout ); ?> ```
274,701
<p>I want to modify the WooCommerce "My Account" left side navigation menu.</p> <p>For that, I have made changes in the <code>woocommerce/templates/myaccount/navigation.php</code>. The problems with this approach are:</p> <ul> <li>I can add the new items <strong>only</strong> at the first or last position in the menu. I'd need them at the 2nd and 3rd position instead....</li> <li>If WC gets updated, it could change...</li> </ul> <p>What is the best way to customize the WooCommerce "My Account" navigation menu at my convenience?</p> <p><a href="https://i.stack.imgur.com/980Bq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/980Bq.png" alt="enter image description here"></a></p>
[ { "answer_id": 277080, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 6, "selected": true, "text": "<p>For that, you do <strong>not</strong> need to modify the <a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php\" rel=\"noreferrer\"><code>woocommerce/templates/myaccount/navigation.php</code></a>.</p>\n\n<p>The best way to customize the \"My Account\" navigation menu items is to use:</p>\n\n<ul>\n<li><a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/wc-account-functions.php#L127\" rel=\"noreferrer\"><code>woocommerce_account_menu_items</code></a> filter hook to add new items to the menu.</li>\n<li><a href=\"http://php.net/manual/fr/function.array-slice.php\" rel=\"noreferrer\"><code>array_slice()</code></a> to reorder them the way you want.</li>\n</ul>\n\n<p>This way, by using <code>woocommerce_account_menu_items</code> filter hook, you integrate <strong>perfectly</strong> your own items to WC, indeed:</p>\n\n<ul>\n<li>Possibility to redefine your own item endpoints via the WC \"Account\" settings page.</li>\n<li>WC updates automatically the item link's URL when, for example, a modification is done to the permalink settings/structure.</li>\n</ul>\n\n<p>Code example:</p>\n\n<pre><code>// Note the low hook priority, this should give to your other plugins the time to add their own items...\nadd_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 );\n\nfunction add_my_menu_items( $items ) {\n $my_items = array(\n // endpoint =&gt; label\n '2nd-item' =&gt; __( '2nd Item', 'my_plugin' ),\n '3rd-item' =&gt; __( '3rd Item', 'my_plugin' ),\n );\n\n $my_items = array_slice( $items, 0, 1, true ) +\n $my_items +\n array_slice( $items, 1, count( $items ), true );\n\n return $my_items;\n}\n</code></pre>\n\n<p><strong>Note 1</strong>: The link's url of your items is defined automatically by WC <a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php#L30\" rel=\"noreferrer\">here</a>. To do that, WC simply append the item endpoint defined in the filter above to the \"My account\" page URL. So define your item endpoints accordingly.</p>\n\n<p><strong>Note 2</strong>: In your question, it seems like you modified the WooCommerce template directly in core...<br />\n<code>woocommerce/templates/myaccount/navigation.php</code> <br />\nWhen you <strong>have to</strong> modify a WC template, the correct way to do it is to duplicate the template's path <strong>relative</strong> to the <code>woocommerce/templates</code> folder into your theme/plugin's <code>woocommerce</code> folder. For example in our case, you'd have to paste the template into:<br />\n<code>child-theme/woocommerce/myaccount/navigation.php</code>.</p>\n" }, { "answer_id": 369323, "author": "Amin", "author_id": 113633, "author_profile": "https://wordpress.stackexchange.com/users/113633", "pm_score": 2, "selected": false, "text": "<p>Well customizing Woocommerce account and adding new items comes in a few steps,</p>\n<p><strong>First Step: Create Links:</strong></p>\n<p>You should use <code>woocommerce_account_menu_items</code> filter to modify existing menu items or adding new menu items, for example i add an item called <strong>Wishlist</strong></p>\n<pre><code>add_filter( 'woocommerce_account_menu_items', function($items) {\n $items['wishlist'] = __('Wishlist', 'textdomain');\n\n return $items;\n}, 99, 1 );\n</code></pre>\n<p><strong>Note:</strong> I've gone through simplest way, you can use <a href=\"https://www.php.net/manual/en/function.array-slice.php\" rel=\"nofollow noreferrer\">array_slice</a> if you want to put menu item at your desired position.</p>\n<p><strong>P.s:</strong> If you want to remove or modify existing items you can do it like this:</p>\n<pre><code>add_filter( 'woocommerce_account_menu_items', function($items) {\n unset($items['downloads']); // Remove downloads item\n $items['orders'] = __('My Orders', 'textdomain'); // Changing label for orders\n\n return $items;\n}, 99, 1 );\n</code></pre>\n<p><strong>Step 2: Add rewrite end points:</strong></p>\n<p>For each item you add you're gonna need to add an endpoint:</p>\n<pre><code>add_action( 'init', function() {\n add_rewrite_endpoint( 'wishlist', EP_ROOT | EP_PAGES );\n // Repeat above line for more items ...\n} );\n</code></pre>\n<p>Note that after you add new endpoints you need to flush rewrite rules by either going to <em><strong>wp-admin/settings/permalinks</strong></em> and clicking <strong>update</strong> button or with <code>flush_rewrite_rules()</code> function</p>\n<p><strong>Step 3: Display new item content</strong></p>\n<p>To display content for your newly added items you should use <code>woocommerce_account_{myEndPoint}_endpoint</code> action, for our example i created a file called <code>wishlist.php</code> in my themes directory under <code>woocommerce/myaccount/</code> and display it's content like this:</p>\n<pre><code>add_action( 'woocommerce_account_wishlist_endpoint', function() {\n wc_get_template_part('myaccount/wishlist');\n});\n</code></pre>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124605/" ]
I want to modify the WooCommerce "My Account" left side navigation menu. For that, I have made changes in the `woocommerce/templates/myaccount/navigation.php`. The problems with this approach are: * I can add the new items **only** at the first or last position in the menu. I'd need them at the 2nd and 3rd position instead.... * If WC gets updated, it could change... What is the best way to customize the WooCommerce "My Account" navigation menu at my convenience? [![enter image description here](https://i.stack.imgur.com/980Bq.png)](https://i.stack.imgur.com/980Bq.png)
For that, you do **not** need to modify the [`woocommerce/templates/myaccount/navigation.php`](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php). The best way to customize the "My Account" navigation menu items is to use: * [`woocommerce_account_menu_items`](https://github.com/woocommerce/woocommerce/blob/master/includes/wc-account-functions.php#L127) filter hook to add new items to the menu. * [`array_slice()`](http://php.net/manual/fr/function.array-slice.php) to reorder them the way you want. This way, by using `woocommerce_account_menu_items` filter hook, you integrate **perfectly** your own items to WC, indeed: * Possibility to redefine your own item endpoints via the WC "Account" settings page. * WC updates automatically the item link's URL when, for example, a modification is done to the permalink settings/structure. Code example: ``` // Note the low hook priority, this should give to your other plugins the time to add their own items... add_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 ); function add_my_menu_items( $items ) { $my_items = array( // endpoint => label '2nd-item' => __( '2nd Item', 'my_plugin' ), '3rd-item' => __( '3rd Item', 'my_plugin' ), ); $my_items = array_slice( $items, 0, 1, true ) + $my_items + array_slice( $items, 1, count( $items ), true ); return $my_items; } ``` **Note 1**: The link's url of your items is defined automatically by WC [here](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php#L30). To do that, WC simply append the item endpoint defined in the filter above to the "My account" page URL. So define your item endpoints accordingly. **Note 2**: In your question, it seems like you modified the WooCommerce template directly in core... `woocommerce/templates/myaccount/navigation.php` When you **have to** modify a WC template, the correct way to do it is to duplicate the template's path **relative** to the `woocommerce/templates` folder into your theme/plugin's `woocommerce` folder. For example in our case, you'd have to paste the template into: `child-theme/woocommerce/myaccount/navigation.php`.
274,719
<p>I have created my site with pure PHP-code, and now started to migrate it to Wordpress platform. Changing authentication from own system to WP-user meta was quite easy. But when i use user session data for site functions, i have to query now user meta instead of simple MySqli-queries.</p> <p>My old query is like below. Page is getting <code>$provider</code>, what is eMail-address. And with it, can fetch rest of needed values from database:</p> <pre><code>$provider=$_GET['provider']; $providername=mysqli_query($db,"SELECT name,email,phone_number,pic,province,feedback FROM $usertable WHERE email='$provider'"); while($row = mysqli_fetch_array($providername)) { $provname=$row['name']; $provemail=$row['email']; $provpic=$row['pic']; $provphone=$row['phone_number']; $provprovince=$row['province']; $feedback=$row['feedback']; } </code></pre> <p>Simple and working well. But do this same with WP-query. I tried to find solution from number of threads, but no. In my mind didn't get it as it so differently done or samples do not just fit to my need here.</p> <p>Can you help a little bit here? I think that this query can be made with WP-query as simple.</p>
[ { "answer_id": 277080, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 6, "selected": true, "text": "<p>For that, you do <strong>not</strong> need to modify the <a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php\" rel=\"noreferrer\"><code>woocommerce/templates/myaccount/navigation.php</code></a>.</p>\n\n<p>The best way to customize the \"My Account\" navigation menu items is to use:</p>\n\n<ul>\n<li><a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/wc-account-functions.php#L127\" rel=\"noreferrer\"><code>woocommerce_account_menu_items</code></a> filter hook to add new items to the menu.</li>\n<li><a href=\"http://php.net/manual/fr/function.array-slice.php\" rel=\"noreferrer\"><code>array_slice()</code></a> to reorder them the way you want.</li>\n</ul>\n\n<p>This way, by using <code>woocommerce_account_menu_items</code> filter hook, you integrate <strong>perfectly</strong> your own items to WC, indeed:</p>\n\n<ul>\n<li>Possibility to redefine your own item endpoints via the WC \"Account\" settings page.</li>\n<li>WC updates automatically the item link's URL when, for example, a modification is done to the permalink settings/structure.</li>\n</ul>\n\n<p>Code example:</p>\n\n<pre><code>// Note the low hook priority, this should give to your other plugins the time to add their own items...\nadd_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 );\n\nfunction add_my_menu_items( $items ) {\n $my_items = array(\n // endpoint =&gt; label\n '2nd-item' =&gt; __( '2nd Item', 'my_plugin' ),\n '3rd-item' =&gt; __( '3rd Item', 'my_plugin' ),\n );\n\n $my_items = array_slice( $items, 0, 1, true ) +\n $my_items +\n array_slice( $items, 1, count( $items ), true );\n\n return $my_items;\n}\n</code></pre>\n\n<p><strong>Note 1</strong>: The link's url of your items is defined automatically by WC <a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php#L30\" rel=\"noreferrer\">here</a>. To do that, WC simply append the item endpoint defined in the filter above to the \"My account\" page URL. So define your item endpoints accordingly.</p>\n\n<p><strong>Note 2</strong>: In your question, it seems like you modified the WooCommerce template directly in core...<br />\n<code>woocommerce/templates/myaccount/navigation.php</code> <br />\nWhen you <strong>have to</strong> modify a WC template, the correct way to do it is to duplicate the template's path <strong>relative</strong> to the <code>woocommerce/templates</code> folder into your theme/plugin's <code>woocommerce</code> folder. For example in our case, you'd have to paste the template into:<br />\n<code>child-theme/woocommerce/myaccount/navigation.php</code>.</p>\n" }, { "answer_id": 369323, "author": "Amin", "author_id": 113633, "author_profile": "https://wordpress.stackexchange.com/users/113633", "pm_score": 2, "selected": false, "text": "<p>Well customizing Woocommerce account and adding new items comes in a few steps,</p>\n<p><strong>First Step: Create Links:</strong></p>\n<p>You should use <code>woocommerce_account_menu_items</code> filter to modify existing menu items or adding new menu items, for example i add an item called <strong>Wishlist</strong></p>\n<pre><code>add_filter( 'woocommerce_account_menu_items', function($items) {\n $items['wishlist'] = __('Wishlist', 'textdomain');\n\n return $items;\n}, 99, 1 );\n</code></pre>\n<p><strong>Note:</strong> I've gone through simplest way, you can use <a href=\"https://www.php.net/manual/en/function.array-slice.php\" rel=\"nofollow noreferrer\">array_slice</a> if you want to put menu item at your desired position.</p>\n<p><strong>P.s:</strong> If you want to remove or modify existing items you can do it like this:</p>\n<pre><code>add_filter( 'woocommerce_account_menu_items', function($items) {\n unset($items['downloads']); // Remove downloads item\n $items['orders'] = __('My Orders', 'textdomain'); // Changing label for orders\n\n return $items;\n}, 99, 1 );\n</code></pre>\n<p><strong>Step 2: Add rewrite end points:</strong></p>\n<p>For each item you add you're gonna need to add an endpoint:</p>\n<pre><code>add_action( 'init', function() {\n add_rewrite_endpoint( 'wishlist', EP_ROOT | EP_PAGES );\n // Repeat above line for more items ...\n} );\n</code></pre>\n<p>Note that after you add new endpoints you need to flush rewrite rules by either going to <em><strong>wp-admin/settings/permalinks</strong></em> and clicking <strong>update</strong> button or with <code>flush_rewrite_rules()</code> function</p>\n<p><strong>Step 3: Display new item content</strong></p>\n<p>To display content for your newly added items you should use <code>woocommerce_account_{myEndPoint}_endpoint</code> action, for our example i created a file called <code>wishlist.php</code> in my themes directory under <code>woocommerce/myaccount/</code> and display it's content like this:</p>\n<pre><code>add_action( 'woocommerce_account_wishlist_endpoint', function() {\n wc_get_template_part('myaccount/wishlist');\n});\n</code></pre>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124612/" ]
I have created my site with pure PHP-code, and now started to migrate it to Wordpress platform. Changing authentication from own system to WP-user meta was quite easy. But when i use user session data for site functions, i have to query now user meta instead of simple MySqli-queries. My old query is like below. Page is getting `$provider`, what is eMail-address. And with it, can fetch rest of needed values from database: ``` $provider=$_GET['provider']; $providername=mysqli_query($db,"SELECT name,email,phone_number,pic,province,feedback FROM $usertable WHERE email='$provider'"); while($row = mysqli_fetch_array($providername)) { $provname=$row['name']; $provemail=$row['email']; $provpic=$row['pic']; $provphone=$row['phone_number']; $provprovince=$row['province']; $feedback=$row['feedback']; } ``` Simple and working well. But do this same with WP-query. I tried to find solution from number of threads, but no. In my mind didn't get it as it so differently done or samples do not just fit to my need here. Can you help a little bit here? I think that this query can be made with WP-query as simple.
For that, you do **not** need to modify the [`woocommerce/templates/myaccount/navigation.php`](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php). The best way to customize the "My Account" navigation menu items is to use: * [`woocommerce_account_menu_items`](https://github.com/woocommerce/woocommerce/blob/master/includes/wc-account-functions.php#L127) filter hook to add new items to the menu. * [`array_slice()`](http://php.net/manual/fr/function.array-slice.php) to reorder them the way you want. This way, by using `woocommerce_account_menu_items` filter hook, you integrate **perfectly** your own items to WC, indeed: * Possibility to redefine your own item endpoints via the WC "Account" settings page. * WC updates automatically the item link's URL when, for example, a modification is done to the permalink settings/structure. Code example: ``` // Note the low hook priority, this should give to your other plugins the time to add their own items... add_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 ); function add_my_menu_items( $items ) { $my_items = array( // endpoint => label '2nd-item' => __( '2nd Item', 'my_plugin' ), '3rd-item' => __( '3rd Item', 'my_plugin' ), ); $my_items = array_slice( $items, 0, 1, true ) + $my_items + array_slice( $items, 1, count( $items ), true ); return $my_items; } ``` **Note 1**: The link's url of your items is defined automatically by WC [here](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php#L30). To do that, WC simply append the item endpoint defined in the filter above to the "My account" page URL. So define your item endpoints accordingly. **Note 2**: In your question, it seems like you modified the WooCommerce template directly in core... `woocommerce/templates/myaccount/navigation.php` When you **have to** modify a WC template, the correct way to do it is to duplicate the template's path **relative** to the `woocommerce/templates` folder into your theme/plugin's `woocommerce` folder. For example in our case, you'd have to paste the template into: `child-theme/woocommerce/myaccount/navigation.php`.
274,737
<p>How to build this menu in WordPress</p> <pre><code>&lt;div class="collapse navbar-collapse" id="collapse-1"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;our story&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;our vision&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#"&gt;History&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;History 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;History 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;History 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>WordPress Code:</p> <pre><code>&lt;div class="collapse navbar-collapse" id="collapse-1"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'header', 'menu_class' =&gt; 'nav navbar-nav', 'fallback_cb' =&gt; false ) ); ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 274743, "author": "Elidrissi simo", "author_id": 83187, "author_profile": "https://wordpress.stackexchange.com/users/83187", "pm_score": 0, "selected": false, "text": "<p>you can use Walker_Nav_Menu class if you want to modify the default wordpress menu markup.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/Walker</a></p>\n\n<p><a href=\"https://www.youtube.com/watch?v=IqTMhmjTBoE&amp;list=PLriKzYyLb28kpEnFFi9_vJWPf5-_7d3rX&amp;index=19\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=IqTMhmjTBoE&amp;list=PLriKzYyLb28kpEnFFi9_vJWPf5-_7d3rX&amp;index=19</a></p>\n" }, { "answer_id": 274744, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 2, "selected": false, "text": "<p>The easiest way to do this is to use an off-the-shelf solution. There is a WP_Bootstrap_Navwalker class which extends WordPress' native Walker_Nav_Menu class and makes your Navigation Menus ready for Bootstrap 3 or 4. <a href=\"https://github.com/wp-bootstrap/wp-bootstrap-navwalker\" rel=\"nofollow noreferrer\">Download it from GitHub</a>.</p>\n\n<p>Add it to your theme, then add the following to the <code>functions.php</code>:</p>\n\n<pre><code>&lt;?php\nrequire_once('path-to-the-directory/wp-bootstrap-navwalker.php');\n</code></pre>\n\n<p>Change <code>path-to-the-directory/</code> to fit your needs.</p>\n\n<p>Next, alter your <code>wp_nav_menu()</code> with the following code:</p>\n\n<pre><code>&lt;?php\nwp_nav_menu( array(\n 'menu' =&gt; 'header', // match name to yours\n 'theme_location' =&gt; 'header',\n 'container' =&gt; 'div', // no need to wrap `wp_nav_menu` manually\n 'container_class' =&gt; 'collapse navbar-collapse',\n 'container_id' =&gt; 'collapse-1',\n 'menu_class' =&gt; 'nav navbar-nav',\n 'fallback_cb' =&gt; false,\n 'walker' =&gt; new WP_Bootstrap_Navwalker() // Use different Walker\n));\n</code></pre>\n\n<p>Note, that you don't need the <code>&lt;div class=\"collapse navbar-collapse\" id=\"collapse-1\"&gt;</code> anymore as it will be added by <code>wp_nav_menu()</code> with proper CSS classes and <code>id</code>.</p>\n\n<p>Also, read the WP_Bootstrap_Navwalker README.md file carefully.</p>\n" }, { "answer_id": 305052, "author": "Jiwan", "author_id": 143440, "author_profile": "https://wordpress.stackexchange.com/users/143440", "pm_score": 1, "selected": false, "text": "<p>The easiest solution would be to use jquery in this case. You can add a new class in your functions.php file to check if the menu item has children and then add attributes to that item or use bootstrap nav walker as well. Here' I'm going with the easier one.</p>\n\n<pre>\n\n $(document).ready(function(){\n $(\"ul.sub-menu\").parent().addClass(\"dropdown\");\n $(\"ul.sub-menu\").addClass(\"dropdown-menu\");\n $(\"ul#menuid li.dropdown a\").addClass(\"dropdown-toggle\");\n $(\"ul.sub-menu li a\").removeClass(\"dropdown-toggle\"); \n $('.navbar .dropdown-toggle').append('');\n $('a.dropdown-toggle').attr('data-toggle', 'dropdown');\n });\n\n</pre>\n\n<p>Just copy it and paste it in your footer.php.\nFor more details <a href=\"http://webtrickshome.com/faq/how-to-add-bootstrap-dropdown-class-in-wordpress-menu-item\" rel=\"nofollow noreferrer\">http://webtrickshome.com/faq/how-to-add-bootstrap-dropdown-class-in-wordpress-menu-item</a></p>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274737", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124623/" ]
How to build this menu in WordPress ``` <div class="collapse navbar-collapse" id="collapse-1"> <ul class="nav navbar-nav"> <li><a href="#">our story</a></li> <li><a href="#">our vision</a></li> <li class="dropdown"> <a href="#">History</a> <ul class="dropdown-menu"> <li><a href="#">History 1</a></li> <li><a href="#">History 2</a></li> <li><a href="#">History 3</a></li> </ul> </li> </ul> </div> ``` WordPress Code: ``` <div class="collapse navbar-collapse" id="collapse-1"> <?php wp_nav_menu( array( 'theme_location' => 'header', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => false ) ); ?> </div> ```
The easiest way to do this is to use an off-the-shelf solution. There is a WP\_Bootstrap\_Navwalker class which extends WordPress' native Walker\_Nav\_Menu class and makes your Navigation Menus ready for Bootstrap 3 or 4. [Download it from GitHub](https://github.com/wp-bootstrap/wp-bootstrap-navwalker). Add it to your theme, then add the following to the `functions.php`: ``` <?php require_once('path-to-the-directory/wp-bootstrap-navwalker.php'); ``` Change `path-to-the-directory/` to fit your needs. Next, alter your `wp_nav_menu()` with the following code: ``` <?php wp_nav_menu( array( 'menu' => 'header', // match name to yours 'theme_location' => 'header', 'container' => 'div', // no need to wrap `wp_nav_menu` manually 'container_class' => 'collapse navbar-collapse', 'container_id' => 'collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => false, 'walker' => new WP_Bootstrap_Navwalker() // Use different Walker )); ``` Note, that you don't need the `<div class="collapse navbar-collapse" id="collapse-1">` anymore as it will be added by `wp_nav_menu()` with proper CSS classes and `id`. Also, read the WP\_Bootstrap\_Navwalker README.md file carefully.
274,802
<p>Here is code , basically I want to fetch by Post author but not able to solve this any help regards this . </p> <pre><code>&lt;?php global $post; $author = get_the_author(); $args = array( 'author' =&gt;$user_ID, 'posts_per_page' =&gt; $per_page, 'author'=&gt; $author, 'post_type' =&gt; 'ultimate-auction', //'auction-status' =&gt; 'expired', 'post_status' =&gt; 'publish', 'offset' =&gt; $pagination, 'orderby' =&gt; 'meta_value', 'meta_key' =&gt; 'wdm_listing_ends', 'order' =&gt; 'DESC', ); $author_posts = new WP_Query( $args ); if( $author_posts-&gt;have_posts() ) { while( $author_posts-&gt;have_posts()) { $author_posts-&gt;the_post(); ?&gt; &lt;?php the_content();?&gt;&lt;/div&gt; &lt;?php // you should have access to any of the tags you normally // can use in The Loop } wp_reset_postdata(); } ?&gt; </code></pre>
[ { "answer_id": 274771, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>Do <strong>not</strong> rely on changing plugin details to work around this issue. The code that decides a match in official repository is a black box — they don’t disclose how it works and what it considers, except in very general terms. Even if it ignores your plugin <em>today</em>, who knows if it will do the same tomorrow?</p>\n\n<p>Any WP site that runs non–repo extensions <em>needs</em> to properly and definitively block possibility of their breakage from invalid updates.</p>\n\n<p>Personally I got tired of the issue and made my own wheel for it as <a href=\"https://github.com/Rarst/update-blocker\" rel=\"nofollow noreferrer\">Update Blocker</a> plugin. I am sure there are more alternatives around.</p>\n" }, { "answer_id": 274776, "author": "Marc", "author_id": 67391, "author_profile": "https://wordpress.stackexchange.com/users/67391", "pm_score": 2, "selected": true, "text": "<p>I was able to find out that wordpress does cache available updates in the wp_options table in an option named <code>_site_transient_update_plugins</code>.</p>\n\n<p>By clearing this value I was able to get Wordpress to notice my changes. I used the following query:</p>\n\n<p><code>UPDATE wp_options SET option_value='' WHERE option_name='_site_transient_update_plugins';</code></p>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112012/" ]
Here is code , basically I want to fetch by Post author but not able to solve this any help regards this . ``` <?php global $post; $author = get_the_author(); $args = array( 'author' =>$user_ID, 'posts_per_page' => $per_page, 'author'=> $author, 'post_type' => 'ultimate-auction', //'auction-status' => 'expired', 'post_status' => 'publish', 'offset' => $pagination, 'orderby' => 'meta_value', 'meta_key' => 'wdm_listing_ends', 'order' => 'DESC', ); $author_posts = new WP_Query( $args ); if( $author_posts->have_posts() ) { while( $author_posts->have_posts()) { $author_posts->the_post(); ?> <?php the_content();?></div> <?php // you should have access to any of the tags you normally // can use in The Loop } wp_reset_postdata(); } ?> ```
I was able to find out that wordpress does cache available updates in the wp\_options table in an option named `_site_transient_update_plugins`. By clearing this value I was able to get Wordpress to notice my changes. I used the following query: `UPDATE wp_options SET option_value='' WHERE option_name='_site_transient_update_plugins';`
274,810
<p>I'm trying to setup unit tests for a plugin I am developing. I just followed the steps at... <a href="https://make.wordpress.org/cli/handbook/plugin-unit-tests/" rel="nofollow noreferrer">https://make.wordpress.org/cli/handbook/plugin-unit-tests/</a></p> <p>However, when I run <code>phpunit</code> I get the following...</p> <pre><code>$ phpunit Installing... Running as single site... To run multisite, use -c tests/phpunit/multisite.xml Warning: Cannot modify header information - headers already sent by (output started at /private/tmp/wordpress-tests-lib/includes/bootstrap.php:68) in /Users/&lt;USERNAME&gt;/Sites/&lt;MYSITE.COM&gt;/wp-load.php on line 64 </code></pre> <p>I am running...</p> <ul> <li>Mac OS 10.12.6</li> <li>PHP v5.6.30</li> <li>PHPUnit 4.8.36</li> <li>MAMP Pro 4.2</li> </ul> <p>The error noted, <code>bootstrap.php:68</code> which is the start of the program outputting the "Installing..." text from the output noted above. Line 68 reads...</p> <pre><code>system( WP_PHP_BINARY . ' ' . escapeshellarg( dirname( __FILE__ ) . '/install.php' ) . ' ' . escapeshellarg( $config_file_path ) . ' ' . $multisite ); </code></pre>
[ { "answer_id": 274811, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>That problem sounds like your code is sending text/characters to the screen, then it sends out a page 'header' (the <code>&lt;head&gt;</code> part of an HTML page). PHP doesn't like that; once you put any characters on the screen, you can't send out page headers (the <code>&lt;head&gt;</code> part).</p>\n\n<p>Sometimes it is as simple as a space character in front of the <code>&lt;?php</code> code. Check for that, or any other text sent out before the page header.</p>\n" }, { "answer_id": 274869, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 2, "selected": true, "text": "<p>The error is telling you that the code tried to output a HTTP response header with the <code>header()</code> function after the response body has already begun to be sent. As you noted, line 68 of <code>bootstrap.php</code> is calling that script that outputs <code>Installing...</code>. So after that output has already been sent, you can't send a response header.</p>\n\n<p>The next step to debug this is to find out why a response header is being sent. That isn't supposed to be happening, because here we are running the tests from the command line, we're not actually sending a page to the browser.</p>\n\n<p>So, we need to see where <code>header()</code> is being called. The error tells you that it is in <code>wp-load.php</code> on line 64:</p>\n\n<pre><code> header( 'Location: ' . $path );\n</code></pre>\n\n<p>This line itself doesn't tell us much, but we find that it is within a big <code>if ... else</code> statement:</p>\n\n<pre><code>/*\n * If wp-config.php exists in the WordPress root, or if it exists in the root and wp-settings.php\n * doesn't, load wp-config.php. The secondary check for wp-settings.php has the added benefit\n * of avoiding cases where the current directory is a nested installation, e.g. / is WordPress(a)\n * and /blog/ is WordPress(b).\n *\n * If neither set of conditions is true, initiate loading the setup process.\n */\nif ( file_exists( ABSPATH . 'wp-config.php') ) {\n\n /** The config file resides in ABSPATH */\n require_once( ABSPATH . 'wp-config.php' );\n\n} elseif ( @file_exists( dirname( ABSPATH ) . '/wp-config.php' ) &amp;&amp; ! @file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {\n\n /** The config file resides one level above ABSPATH but is not part of another install */\n require_once( dirname( ABSPATH ) . '/wp-config.php' );\n\n} else {\n\n // snip\n\n header( 'Location: ' . $path );\n\n // snip\n\n}\n</code></pre>\n\n<p>Essentially what this tells us is that <code>wp-load.php</code> is looking for the <code>wp-config.php</code> file, and isn't finding it. So it is initiating the set-up process, and as part of that it is trying to redirect to the installation page by sending the <code>Location</code> header.</p>\n\n<p>So you apparently have not set up your <code>wp-config.php</code> file correctly.</p>\n\n<p>The <code>wp-config.php</code> file was supposed to be set up by the script you ran though, so this is likely an indicator that something failed. In fact, since we are running the tests here, the <code>wp-tests-config.php</code> file is expected to be used instead. So the next step is figuring out why <code>wp-tests-config.php</code> isn't being loaded. You should be able to find that file in the <code>/tmp/wordpress-tests-lib/</code> directory. </p>\n" } ]
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274810", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28787/" ]
I'm trying to setup unit tests for a plugin I am developing. I just followed the steps at... <https://make.wordpress.org/cli/handbook/plugin-unit-tests/> However, when I run `phpunit` I get the following... ``` $ phpunit Installing... Running as single site... To run multisite, use -c tests/phpunit/multisite.xml Warning: Cannot modify header information - headers already sent by (output started at /private/tmp/wordpress-tests-lib/includes/bootstrap.php:68) in /Users/<USERNAME>/Sites/<MYSITE.COM>/wp-load.php on line 64 ``` I am running... * Mac OS 10.12.6 * PHP v5.6.30 * PHPUnit 4.8.36 * MAMP Pro 4.2 The error noted, `bootstrap.php:68` which is the start of the program outputting the "Installing..." text from the output noted above. Line 68 reads... ``` system( WP_PHP_BINARY . ' ' . escapeshellarg( dirname( __FILE__ ) . '/install.php' ) . ' ' . escapeshellarg( $config_file_path ) . ' ' . $multisite ); ```
The error is telling you that the code tried to output a HTTP response header with the `header()` function after the response body has already begun to be sent. As you noted, line 68 of `bootstrap.php` is calling that script that outputs `Installing...`. So after that output has already been sent, you can't send a response header. The next step to debug this is to find out why a response header is being sent. That isn't supposed to be happening, because here we are running the tests from the command line, we're not actually sending a page to the browser. So, we need to see where `header()` is being called. The error tells you that it is in `wp-load.php` on line 64: ``` header( 'Location: ' . $path ); ``` This line itself doesn't tell us much, but we find that it is within a big `if ... else` statement: ``` /* * If wp-config.php exists in the WordPress root, or if it exists in the root and wp-settings.php * doesn't, load wp-config.php. The secondary check for wp-settings.php has the added benefit * of avoiding cases where the current directory is a nested installation, e.g. / is WordPress(a) * and /blog/ is WordPress(b). * * If neither set of conditions is true, initiate loading the setup process. */ if ( file_exists( ABSPATH . 'wp-config.php') ) { /** The config file resides in ABSPATH */ require_once( ABSPATH . 'wp-config.php' ); } elseif ( @file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! @file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) { /** The config file resides one level above ABSPATH but is not part of another install */ require_once( dirname( ABSPATH ) . '/wp-config.php' ); } else { // snip header( 'Location: ' . $path ); // snip } ``` Essentially what this tells us is that `wp-load.php` is looking for the `wp-config.php` file, and isn't finding it. So it is initiating the set-up process, and as part of that it is trying to redirect to the installation page by sending the `Location` header. So you apparently have not set up your `wp-config.php` file correctly. The `wp-config.php` file was supposed to be set up by the script you ran though, so this is likely an indicator that something failed. In fact, since we are running the tests here, the `wp-tests-config.php` file is expected to be used instead. So the next step is figuring out why `wp-tests-config.php` isn't being loaded. You should be able to find that file in the `/tmp/wordpress-tests-lib/` directory.
274,816
<p>I have a featured image preview in column view in my Custom Post Types. Now I want to change the size of it. This is my code:</p> <pre><code>add_filter('manage_posts_columns', 'add_img_column'); add_filter('manage_posts_custom_column', 'manage_img_column', 10, 2); function add_img_column($columns) { $columns['img'] = 'Featured Image'; return $columns; } function manage_img_column($column_name, $post_id) { if( $column_name == 'img' ) { echo get_the_post_thumbnail($post_id, 'thumbnail'); return true; } } </code></pre> <p>And I see it like this:</p> <p><a href="https://i.stack.imgur.com/GWhh5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GWhh5.png" alt="enter image description here"></a></p> <p>So know I want to change the size of this image in this view... how... how can I get that? :)</p>
[ { "answer_id": 274817, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": false, "text": "<p>You can create a new size with the funcion <code>add_image_size</code>, example:</p>\n\n<pre><code>add_image_size('my_new_size', 50, 50, true);\n</code></pre>\n\n<p>an then when you get the post thumbnail you select this size, like this:</p>\n\n<pre><code>function manage_img_column($column_name, $post_id) {\n if( $column_name == 'img' ) {\n echo get_the_post_thumbnail($post_id, 'my_new_size');\n return true;\n }\n}\n</code></pre>\n\n<p>See the <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow noreferrer\">Codex</a> for reference.</p>\n" }, { "answer_id": 274818, "author": "frenchy black", "author_id": 28580, "author_profile": "https://wordpress.stackexchange.com/users/28580", "pm_score": 1, "selected": true, "text": "<p>In functions.php :\nMake sure featured images are enabled</p>\n\n<pre><code>add_theme_support( 'post-thumbnails' );\n</code></pre>\n\n<p>then add </p>\n\n<pre><code>add_image_size( 'thumbnail-news', '100', '75', true );\n</code></pre>\n\n<p>And in the code above change </p>\n\n<pre><code>echo get_the_post_thumbnail($post_id, 'thumbnail');\n</code></pre>\n\n<p>to</p>\n\n<pre><code>echo get_the_post_thumbnail($post_id, 'thumbnail-news');\n</code></pre>\n\n<p></p>\n" } ]
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I have a featured image preview in column view in my Custom Post Types. Now I want to change the size of it. This is my code: ``` add_filter('manage_posts_columns', 'add_img_column'); add_filter('manage_posts_custom_column', 'manage_img_column', 10, 2); function add_img_column($columns) { $columns['img'] = 'Featured Image'; return $columns; } function manage_img_column($column_name, $post_id) { if( $column_name == 'img' ) { echo get_the_post_thumbnail($post_id, 'thumbnail'); return true; } } ``` And I see it like this: [![enter image description here](https://i.stack.imgur.com/GWhh5.png)](https://i.stack.imgur.com/GWhh5.png) So know I want to change the size of this image in this view... how... how can I get that? :)
In functions.php : Make sure featured images are enabled ``` add_theme_support( 'post-thumbnails' ); ``` then add ``` add_image_size( 'thumbnail-news', '100', '75', true ); ``` And in the code above change ``` echo get_the_post_thumbnail($post_id, 'thumbnail'); ``` to ``` echo get_the_post_thumbnail($post_id, 'thumbnail-news'); ```
274,861
<p>I've written a function to get products by price range. All works, but now I need add a extra meta key, that will be like 50 - 100 and featured, but code is not returning any products. What is wrong on this code?</p> <pre><code> function product_price_filter_box($attr) { $limit = intval($attr['limit']); $min = intval($attr['min']); $max = intval($attr['max']); $query = array( 'post_status' =&gt; 'publish', 'post_type' =&gt; 'product', 'posts_per_page' =&gt; $limit, 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; '_price', 'value' =&gt; array($min, $max), 'compare' =&gt; 'BETWEEN', 'type' =&gt; 'NUMERIC' ), array( 'key' =&gt; 'featured', 'value' =&gt; '1', 'compare' =&gt; '=', ), ) ); $wpquery = new WP_Query($query); while ( $wpquery-&gt;have_posts() ) : $wpquery-&gt;the_post(); global $product; wc_get_template_part( 'content', 'product' ); endwhile; wp_reset_query(); } add_shortcode( 'product_price_filter_box', 'product_price_filter_box' ); </code></pre>
[ { "answer_id": 276424, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>The featured product's meta key is <code>_featured</code>, but you are using <code>featured</code> in your meta query. This will return no products, since the key doesn't exist.</p>\n\n<p>Also, as far as I know, the value of the key is <code>yes</code>, so your arguments should be like this:</p>\n\n<pre><code>array(\n 'key' =&gt; '_featured',\n 'value' =&gt; 'yes',\n)\n</code></pre>\n\n<p>Another note, is to use the proper way to get the shortcode's attribute. You can do so by using <code>shortcode_atts()</code> function. Here is the syntax for your case:</p>\n\n<pre><code>$atts = shortcode_atts(\n array(\n 'limit' =&gt; '20',\n 'min' =&gt; '1'\n 'max' =&gt; '2'\n ), \n $atts, \n 'product_price_filter_box' \n);\n\n$limit = intval($atts['limit']);\n$min = intval($atts['min']);\n$max = intval($atts['max']);\n</code></pre>\n\n<p>You might want to limit the maximum posts a user can get. This can be done by using the <code>min()</code> function:</p>\n\n<pre><code>$limit = min(20, $limit);\n</code></pre>\n\n<p>And a final note. If you are using <code>WP_Query</code>, you should use <code>wp_reset_postdata();</code> instead of <code>wp_reset_query();</code>, which is used after you use <code>query_posts();</code>.</p>\n" }, { "answer_id": 327204, "author": "Bjorn", "author_id": 83707, "author_profile": "https://wordpress.stackexchange.com/users/83707", "pm_score": 0, "selected": false, "text": "<p>Since WC 3.0.0</p>\n\n<p>You can use <code>wc_get_min_max_price_meta_query()</code>. Woocommerce will create the price min/max meta_query for you. This also includes a tax check.</p>\n\n<p>More info <a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_min_max_price_meta_query.html#740-777\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Below an example that matches the OP question:</p>\n\n<pre><code>$meta_query = array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'your_custom_meta_key',\n 'value' =&gt; '1',\n 'compare' =&gt; '=',\n ),\n);\n$meta_query[] = wc_get_min_max_price_meta_query(array(\n 'min_price' =&gt; 100,\n 'max_price' =&gt; 200,\n));\n$query = array(\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; 'product',\n 'posts_per_page' =&gt; -1,\n 'meta_query' =&gt; $meta_query,\n);\n$wpquery = new WP_Query($query);\n</code></pre>\n" } ]
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44844/" ]
I've written a function to get products by price range. All works, but now I need add a extra meta key, that will be like 50 - 100 and featured, but code is not returning any products. What is wrong on this code? ``` function product_price_filter_box($attr) { $limit = intval($attr['limit']); $min = intval($attr['min']); $max = intval($attr['max']); $query = array( 'post_status' => 'publish', 'post_type' => 'product', 'posts_per_page' => $limit, 'meta_query' => array( 'relation' => 'AND', array( 'key' => '_price', 'value' => array($min, $max), 'compare' => 'BETWEEN', 'type' => 'NUMERIC' ), array( 'key' => 'featured', 'value' => '1', 'compare' => '=', ), ) ); $wpquery = new WP_Query($query); while ( $wpquery->have_posts() ) : $wpquery->the_post(); global $product; wc_get_template_part( 'content', 'product' ); endwhile; wp_reset_query(); } add_shortcode( 'product_price_filter_box', 'product_price_filter_box' ); ```
The featured product's meta key is `_featured`, but you are using `featured` in your meta query. This will return no products, since the key doesn't exist. Also, as far as I know, the value of the key is `yes`, so your arguments should be like this: ``` array( 'key' => '_featured', 'value' => 'yes', ) ``` Another note, is to use the proper way to get the shortcode's attribute. You can do so by using `shortcode_atts()` function. Here is the syntax for your case: ``` $atts = shortcode_atts( array( 'limit' => '20', 'min' => '1' 'max' => '2' ), $atts, 'product_price_filter_box' ); $limit = intval($atts['limit']); $min = intval($atts['min']); $max = intval($atts['max']); ``` You might want to limit the maximum posts a user can get. This can be done by using the `min()` function: ``` $limit = min(20, $limit); ``` And a final note. If you are using `WP_Query`, you should use `wp_reset_postdata();` instead of `wp_reset_query();`, which is used after you use `query_posts();`.
274,864
<p>How can I load Google font only if custom logo is not uploaded?</p> <p>I know how to load resource if we are on this or that page, but not sure how to do this?</p>
[ { "answer_id": 274865, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>The code is not tested but is a good starting point, you may need to add action to enqueue the css or you can write a functions and add the code below into it. </p>\n\n<pre><code> // Enable Custom Logo\n add_theme_support( 'custom-logo', array(\n 'height' =&gt; 200,\n 'width' =&gt; 400,\n 'flex-width' =&gt; true,\n ) );\n\n $old_logo = get_theme_mod( 'header_logo' );\n if ( $old_logo ) {\n\n wp_enqueue_style( 'wpse_89494_style_3', get_template_directory_uri() . '/your-style_3.css' );\n\n }\n</code></pre>\n" }, { "answer_id": 274866, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>There is a function for this purpose, called <a href=\"https://developer.wordpress.org/reference/functions/has_custom_logo/\" rel=\"nofollow noreferrer\"><code>has_custom_logo()</code></a>. You can check whether the website has a custom logo or not by having this conditional:</p>\n\n<pre><code>if ( ! has_custom_logo() ) {\n // Enqueue some google fonts\n wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css?family=Roboto:400' );\n}\n</code></pre>\n" } ]
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66784/" ]
How can I load Google font only if custom logo is not uploaded? I know how to load resource if we are on this or that page, but not sure how to do this?
There is a function for this purpose, called [`has_custom_logo()`](https://developer.wordpress.org/reference/functions/has_custom_logo/). You can check whether the website has a custom logo or not by having this conditional: ``` if ( ! has_custom_logo() ) { // Enqueue some google fonts wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css?family=Roboto:400' ); } ```
274,885
<p>It would be a right way to enqueue the scripts using foreach loop only for <code>jquery</code>, <code>jquery-ui-widge</code>t, <code>jquery-UI-accordion</code>, <code>jquery-ui-slider</code>, <code>jquery-ui-tabs</code>, <code>jquery-ui-datepicker</code>, <code>Jquery-ui-dialog</code> and <code>Jquery-ui-button</code> because I have to write it many times so </p> <p>I have make it like this:</p> <pre><code> $jquery_ui = array( 'jquery', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-accordion', 'jquery-ui-slider', 'jquery-ui-tabs', 'jquery-ui-datepicker', 'jquery-ui-dialog', 'jquery-ui-button', ); // Framework JS foreach ($jquery_ui as $ui) { wp_enqueue_script($ui); } </code></pre> <p>So I just want to know this laziness is a right way or not:)</p>
[ { "answer_id": 274887, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. But to make sure the script has not already been registered or enqueued, use <a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\"><code>wp_script_is()</code></a> as follows:</p>\n\n<pre><code>foreach( $jquery_ui as $ui ) {\n if( !wp_script_is( $ui ) ) {\n wp_enqueue_script( $ui );\n }\n}\n</code></pre>\n\n<p>This will prevent conflicts due to another instance of the script being already enqueued.</p>\n" }, { "answer_id": 282975, "author": "shea", "author_id": 19726, "author_profile": "https://wordpress.stackexchange.com/users/19726", "pm_score": 0, "selected": false, "text": "<p>It is actually even easier than that. <code>wp_enqueue_script()</code> accepts an array of script handles, so you can simply do this:</p>\n\n<pre><code>$jquery_ui = array(\n 'jquery',\n 'jquery-ui-core',\n 'jquery-ui-widget',\n 'jquery-ui-accordion',\n 'jquery-ui-slider',\n 'jquery-ui-tabs',\n 'jquery-ui-datepicker',\n 'jquery-ui-dialog',\n 'jquery-ui-button',\n );\n\nwp_enqueue_script( $jquery_ui );\n</code></pre>\n\n<p>There is no need to check whether the script has already been registered using <code>wp_script_is()</code>, as <code>wp_enqueue_script()</code> handles this for you and will never enqueue the same script (handle) twice. By calling <code>wp_script_is()</code> as well, you are performing an identical check twice unnecessarily. </p>\n" } ]
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108146/" ]
It would be a right way to enqueue the scripts using foreach loop only for `jquery`, `jquery-ui-widge`t, `jquery-UI-accordion`, `jquery-ui-slider`, `jquery-ui-tabs`, `jquery-ui-datepicker`, `Jquery-ui-dialog` and `Jquery-ui-button` because I have to write it many times so I have make it like this: ``` $jquery_ui = array( 'jquery', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-accordion', 'jquery-ui-slider', 'jquery-ui-tabs', 'jquery-ui-datepicker', 'jquery-ui-dialog', 'jquery-ui-button', ); // Framework JS foreach ($jquery_ui as $ui) { wp_enqueue_script($ui); } ``` So I just want to know this laziness is a right way or not:)
Yes you can. But to make sure the script has not already been registered or enqueued, use [`wp_script_is()`](https://codex.wordpress.org/Function_Reference/wp_script_is) as follows: ``` foreach( $jquery_ui as $ui ) { if( !wp_script_is( $ui ) ) { wp_enqueue_script( $ui ); } } ``` This will prevent conflicts due to another instance of the script being already enqueued.
274,908
<p>I have a wordpress site on main.com and a second one on blog.main.com</p> <p>main.com already had an ssl certificate working.</p> <p>In cPanel I installed a new wildcard ssl certificate intended for '*.main.com'</p> <p>(sorry, apparently i don't have enough reputation to post more than 2 links)</p> <p>At this point: https main.com was continuing to function properly.</p> <p>http blog.main.com was still working.</p> <p>https blog.main.com was redirecting to https main.com</p> <p>So the blog needs more work. </p> <p>I changed the wordpress site-url and site-address of the blog to '<a href="https://blog.main.com" rel="nofollow noreferrer">https://blog.main.com</a>'.</p> <p>And I changed the .htaccess of the blog and added 3 lines on top:</p> <pre><code>RewriteEngine on RewriteCond %{HTTPS} !=on [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Now: https blog.main.com still redirects to https main.com.</p> <p>http blog.main.com also redirects to https main.com.</p> <p>(Changing the site-url and address and the .htaccess back, doesn't reverse the redirect.)</p> <p>The only redirect in cPanel is 403 for '.(htaccess|htpasswd|errordocs|logs)$'</p> <p>edit: Note that mail.main.com is also redirecting the main.com.</p> <p>What could be causing the blog to redirect to the main site.</p>
[ { "answer_id": 274887, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. But to make sure the script has not already been registered or enqueued, use <a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\"><code>wp_script_is()</code></a> as follows:</p>\n\n<pre><code>foreach( $jquery_ui as $ui ) {\n if( !wp_script_is( $ui ) ) {\n wp_enqueue_script( $ui );\n }\n}\n</code></pre>\n\n<p>This will prevent conflicts due to another instance of the script being already enqueued.</p>\n" }, { "answer_id": 282975, "author": "shea", "author_id": 19726, "author_profile": "https://wordpress.stackexchange.com/users/19726", "pm_score": 0, "selected": false, "text": "<p>It is actually even easier than that. <code>wp_enqueue_script()</code> accepts an array of script handles, so you can simply do this:</p>\n\n<pre><code>$jquery_ui = array(\n 'jquery',\n 'jquery-ui-core',\n 'jquery-ui-widget',\n 'jquery-ui-accordion',\n 'jquery-ui-slider',\n 'jquery-ui-tabs',\n 'jquery-ui-datepicker',\n 'jquery-ui-dialog',\n 'jquery-ui-button',\n );\n\nwp_enqueue_script( $jquery_ui );\n</code></pre>\n\n<p>There is no need to check whether the script has already been registered using <code>wp_script_is()</code>, as <code>wp_enqueue_script()</code> handles this for you and will never enqueue the same script (handle) twice. By calling <code>wp_script_is()</code> as well, you are performing an identical check twice unnecessarily. </p>\n" } ]
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274908", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124714/" ]
I have a wordpress site on main.com and a second one on blog.main.com main.com already had an ssl certificate working. In cPanel I installed a new wildcard ssl certificate intended for '\*.main.com' (sorry, apparently i don't have enough reputation to post more than 2 links) At this point: https main.com was continuing to function properly. http blog.main.com was still working. https blog.main.com was redirecting to https main.com So the blog needs more work. I changed the wordpress site-url and site-address of the blog to '<https://blog.main.com>'. And I changed the .htaccess of the blog and added 3 lines on top: ``` RewriteEngine on RewriteCond %{HTTPS} !=on [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # 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 ``` Now: https blog.main.com still redirects to https main.com. http blog.main.com also redirects to https main.com. (Changing the site-url and address and the .htaccess back, doesn't reverse the redirect.) The only redirect in cPanel is 403 for '.(htaccess|htpasswd|errordocs|logs)$' edit: Note that mail.main.com is also redirecting the main.com. What could be causing the blog to redirect to the main site.
Yes you can. But to make sure the script has not already been registered or enqueued, use [`wp_script_is()`](https://codex.wordpress.org/Function_Reference/wp_script_is) as follows: ``` foreach( $jquery_ui as $ui ) { if( !wp_script_is( $ui ) ) { wp_enqueue_script( $ui ); } } ``` This will prevent conflicts due to another instance of the script being already enqueued.
274,941
<p>Is there a way to set an alias on the meta_query arguments when running a <code>get_posts()</code>? One of my queries is performing poorly. To optimize I just need to be able to reuse the same joined table instead of joining in 3 tables when only one is needed.</p> <p>My current example...</p> <pre><code>$args = array( 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'abc_type', 'value' =&gt; array('puppy', 'kitten'), 'compare' =&gt; 'IN', ), array( 'relation' =&gt; 'OR', array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'abc_type', 'value' =&gt; 'puppy', 'compare' =&gt; '=', ), array( 'key' =&gt; 'abc_color', 'value' =&gt; 'pink', 'compare' =&gt; '=', ), ), array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'abc_type', 'value' =&gt; 'kitten', 'compare' =&gt; '=', ), array( 'key' =&gt; 'abc_size', 'value' =&gt; 'large', 'compare' =&gt; '=', ), ), ), ) ); get_posts($args); </code></pre> <p>which basically translates to this in straight SQL...</p> <pre class="lang-sql prettyprint-override"><code>SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) INNER JOIN postmeta AS mt3 ON ( posts.ID = mt3.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value &gt; 'pink' ) ) OR ( ( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' ) AND ( mt4.meta_key = 'abc_size' AND mt4.meta_value = 'large' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; </code></pre> <p>However, this is adding 2 extra joins for the custom meta field <code>abc_type</code> and as such performance has taken a big hit. Is there a way to be able to reference the same alias for multiple meta_query arguments? Basically, <code>mt1</code> and <code>mt3</code> are totally unnecessary, I should just be able to reference the first <code>postmeta</code> table that is used with the first <code>( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') )</code>. Or at least if I can set a custom alias on each of these I could reference that.</p> <p>A more optimal query would be...</p> <pre class="lang-sql prettyprint-override"><code>SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' ) AND ( mt1.meta_key = 'abc_color' AND mt1.meta_value &gt; 'pink' ) ) OR ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value = 'green' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; </code></pre> <p>Thoughts?</p>
[ { "answer_id": 274944, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>I'm not really a database guy, but I played one on TV once...</p>\n\n<p>Wouldn't this part</p>\n\n<pre><code>SELECT posts.* FROM posts\nINNER JOIN postmeta ON ( posts.ID = postmeta.post_id )\nINNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id )\nINNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id )\n</code></pre>\n\n<p>be better replaced with</p>\n\n<pre><code>SELECT posts.* FROM posts\nINNER JOIN postmeta ON (( posts.ID = postmeta.post_id ) and \n( posts.ID = mt1.post_id ) and\n( posts.ID = mt2.post_id ))\n</code></pre>\n\n<p>That could probably be simplified even more..with some alias stuck in there in the proper place so you could use the rest of your query.</p>\n\n<p>Just a thought...</p>\n" }, { "answer_id": 292230, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>posts_where</code> and <code>posts_join</code> filters to modify the query. It's not very elegant, but you should be able to mess with these two filters so that your sql is more optimized. It's kind of brute-forcey, but I can't see a better way in the WP_Query class. That's not saying there isn't though.</p>\n\n<pre><code>//* Make sure to not suppress filters\n$args = array(\n 'suppress_filters' =&gt; false,\n //* rest of args unchanged\n);\n\nadd_filter( 'posts_where', function( $sql ) {\n $sql = str_replace(\n \"( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' )\",\n \"( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' )\",\n $sql\n );\n\n $sql = str_replace(\n \"( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' )\",\n \"( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' )\",\n $sql\n );\n\n $sql = str_replace( [ 'mt2', 'mt4' ], [ 'mt1', 'mt2' ], $sql );\n return $sql;\n});\n\nadd_filter( 'posts_join', function( $sql ) {\n $sql = str_replace(\n \" INNER JOIN wp_postmeta AS mt4 ON ( wp_posts.ID = mt4.post_id )\",\n \"\",\n $sql\n );\n $sql = str_replace(\n \" INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id )\",\n \"\",\n $sql\n );\n return $sql;\n});\n</code></pre>\n\n<p>There should probably be some checks in there so that you're not accidentally modifying other queries. That's left as an exercise for the reader.</p>\n" }, { "answer_id": 292333, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": false, "text": "<p>Have a look at the <code>meta_query_find_compatible_table_alias</code> filter defined in <code>wp-includes/class-wp-meta-query.php</code>. This filter's documentation:</p>\n\n<pre><code>/**\n * Filters the table alias identified as compatible with the current clause.\n *\n * @since 4.1.0\n *\n * @param string|bool $alias Table alias, or false if none was found.\n * @param array $clause First-order query clause.\n * @param array $parent_query Parent of $clause.\n * @param object $this WP_Meta_Query object.\n */\nreturn apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this );\n</code></pre>\n\n<p>It's likely that the calling function, <code>find_compatible_table_alias</code>, is returning false and thus the query creates the <code>mt*</code> aliases. Here is some sample code using this filter, although I would personally advocate for something that's a little easier to understand. Modifying queries like this can lead to tons of headaches down the road and it may not be apparent at all where the query is getting messed up, especially if you bring in other developers in the future. That said...</p>\n\n<pre><code>// Reuse the same alias for the abc_type meta key.\nfunction pets_modify_meta_query( $alias, $meta_query ) {\n if ( 'abc_type' === $meta_query['key'] ) {\n return 'mt1';\n }\n\n return $alias;\n}\n\n// Filter the query.\nadd_filter( 'meta_query_find_compatible_table_alias', 'pets_modify_meta_query', 10, 2 );\n\n$args = array(\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'abc_type',\n 'value' =&gt; array('puppy', 'kitten'),\n 'compare' =&gt; 'IN',\n ),\n array(\n 'relation' =&gt; 'OR',\n array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'abc_type',\n 'value' =&gt; 'puppy',\n 'compare' =&gt; '=',\n ),\n array(\n 'key' =&gt; 'abc_color',\n 'value' =&gt; 'pink',\n 'compare' =&gt; '=',\n ),\n ),\n array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'abc_type',\n 'value' =&gt; 'kitten',\n 'compare' =&gt; '=',\n ),\n array(\n 'key' =&gt; 'abc_size',\n 'value' =&gt; 'large',\n 'compare' =&gt; '=',\n ),\n ),\n ),\n )\n);\n\n$q = new WP_Query($args);\necho '&lt;pre&gt;', print_r($q-&gt;request, true); die;\n</code></pre>\n\n<p>This results in a query like</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS\n wp_posts.ID\nFROM wp_posts\nINNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )\nINNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )\nWHERE\n 1=1\nAND\n(\n ( mt1.meta_key = 'abc_type' AND mt1.meta_value IN ('puppy','kitten') )\n AND\n (\n (\n ( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' )\n AND\n ( wp_postmeta.meta_key = 'abc_color' AND wp_postmeta.meta_value = 'pink' )\n )\n OR\n (\n ( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'kitten' )\n AND\n ( mt1.meta_key = 'abc_size' AND mt1.meta_value = 'large' )\n )\n )\n)\nAND\n wp_posts.post_type = 'post'\nAND (\n wp_posts.post_status = 'publish'\n OR\n wp_posts.post_status = 'future'\n OR\n wp_posts.post_status = 'draft'\n OR wp_posts.post_status = 'pending'\n)\nGROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n" }, { "answer_id": 292408, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 0, "selected": false, "text": "<p>You could optimize your query by removing the first meta query as it is redundant, like so:</p>\n\n<pre><code>$args = array(\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'abc_type',\n 'value' =&gt; 'puppy',\n 'compare' =&gt; '=',\n ),\n array(\n 'key' =&gt; 'abc_color',\n 'value' =&gt; 'pink',\n 'compare' =&gt; '=',\n ),\n ),\n array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'abc_type',\n 'value' =&gt; 'kitten',\n 'compare' =&gt; '=',\n ),\n array(\n 'key' =&gt; 'abc_size',\n 'value' =&gt; 'large',\n 'compare' =&gt; '=',\n ),\n ),\n ),\n);\nget_posts($args);\n</code></pre>\n\n<p>This way you will only get either <code>pink puppy</code> or <code>large kitten</code>, as you intend, I believe.</p>\n\n<p>As for optimizing WordPress's internal MySQL queries, I believe you should stay clear of that since you would expose yourself to possible side effects. You would be better off relying on the fact that queries are cached and do some more PHP processing on the (larger) data set. I believe this will lead to better performance overall as the bottleneck is not the amount of data you are extracting from the database, but the difficulty with which is it gathered (how many queries). PHP is quite fast as coming through arrays.</p>\n\n<p>So I believe a situation like this is faster, considering that the post meta gets cached:</p>\n\n<pre><code>$args = array(\n 'meta_query' =&gt; array( \n array(\n 'key' =&gt; 'abc_type',\n 'value' =&gt; array('puppy', 'kitten'),\n 'compare' =&gt; 'IN',\n ),\n ),\n);\n\n$final_posts = array();\nforeach( $get_posts($args) as $post ) {\n if ( 'puppy' === get_post_meta( $post-&gt;ID, 'abc_type', true ) ) {\n if ( 'pink' === get_post_meta( $post-&gt;ID, 'abc_color', true ) ) {\n $final_posts[] = $post;\n }\n } else {\n // This is definitely a kitten\n if ( 'large' === get_post_meta( $post-&gt;ID, 'abc_size', true ) ) {\n $final_posts[] = $post;\n }\n }\n}\n</code></pre>\n" } ]
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28787/" ]
Is there a way to set an alias on the meta\_query arguments when running a `get_posts()`? One of my queries is performing poorly. To optimize I just need to be able to reuse the same joined table instead of joining in 3 tables when only one is needed. My current example... ``` $args = array( 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'abc_type', 'value' => array('puppy', 'kitten'), 'compare' => 'IN', ), array( 'relation' => 'OR', array( 'relation' => 'AND', array( 'key' => 'abc_type', 'value' => 'puppy', 'compare' => '=', ), array( 'key' => 'abc_color', 'value' => 'pink', 'compare' => '=', ), ), array( 'relation' => 'AND', array( 'key' => 'abc_type', 'value' => 'kitten', 'compare' => '=', ), array( 'key' => 'abc_size', 'value' => 'large', 'compare' => '=', ), ), ), ) ); get_posts($args); ``` which basically translates to this in straight SQL... ```sql SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) INNER JOIN postmeta AS mt3 ON ( posts.ID = mt3.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value > 'pink' ) ) OR ( ( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' ) AND ( mt4.meta_key = 'abc_size' AND mt4.meta_value = 'large' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; ``` However, this is adding 2 extra joins for the custom meta field `abc_type` and as such performance has taken a big hit. Is there a way to be able to reference the same alias for multiple meta\_query arguments? Basically, `mt1` and `mt3` are totally unnecessary, I should just be able to reference the first `postmeta` table that is used with the first `( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') )`. Or at least if I can set a custom alias on each of these I could reference that. A more optimal query would be... ```sql SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' ) AND ( mt1.meta_key = 'abc_color' AND mt1.meta_value > 'pink' ) ) OR ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value = 'green' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; ``` Thoughts?
You can use the `posts_where` and `posts_join` filters to modify the query. It's not very elegant, but you should be able to mess with these two filters so that your sql is more optimized. It's kind of brute-forcey, but I can't see a better way in the WP\_Query class. That's not saying there isn't though. ``` //* Make sure to not suppress filters $args = array( 'suppress_filters' => false, //* rest of args unchanged ); add_filter( 'posts_where', function( $sql ) { $sql = str_replace( "( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' )", "( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' )", $sql ); $sql = str_replace( "( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' )", "( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' )", $sql ); $sql = str_replace( [ 'mt2', 'mt4' ], [ 'mt1', 'mt2' ], $sql ); return $sql; }); add_filter( 'posts_join', function( $sql ) { $sql = str_replace( " INNER JOIN wp_postmeta AS mt4 ON ( wp_posts.ID = mt4.post_id )", "", $sql ); $sql = str_replace( " INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id )", "", $sql ); return $sql; }); ``` There should probably be some checks in there so that you're not accidentally modifying other queries. That's left as an exercise for the reader.
274,947
<p>The AdWords Documentation on how to <a href="https://support.google.com/adwords/answer/6095947?hl=en" rel="nofollow noreferrer">Track transaction-specific conversion values</a> states a PHP code as such:</p> <pre><code>&lt;!-- Google Code for Purchase Conversion Page --&gt; &lt;script type="text/javascript"&gt; /* &lt;![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (&lt;? echo $totalValue ?&gt;) { var google_conversion_value = &lt;? echo $totalValue ?&gt;; var google_conversion_currency = &lt;? echo $currency ?&gt;; } var google_remarketing_only = false; /* ]]&gt; */ &lt;/script&gt; &lt;script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"&gt; &lt;/script&gt; &lt;noscript&gt; &lt;div style="display:inline;"&gt; &lt;img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= &lt;? echo $totalValue ?&gt;&amp;amp;currency_code=&lt;? echo $currency ?&gt; &amp;amp;label=xxxxXXx1xXXX123X1xX&amp;amp;guid=ON&amp;amp;script=0"&gt; &lt;/div&gt; &lt;/noscript&gt; &lt;/body&gt; </code></pre> <p>This indicates to me two things:</p> <ol> <li>We need to put the total order value in a <code>$totalValue</code> variable and the currency value into <code>$currency</code>.</li> <li>It should be placed at the end of the <code>&lt;/body&gt;</code> on the page.</li> </ol> <p>Aside from creating your own custom 'Thank You' page on Order Completion and adding it where you want in a custom page template, what's the best way to hook onto the default 'Thank You' page?</p> <p>The WooCommerce Documentation has something on <a href="https://docs.woocommerce.com/document/custom-tracking-code-for-the-thanks-page/" rel="nofollow noreferrer">Custom tracking code for the thanks page</a> that just simply hooks onto <code>woocommerce_thankyou</code>. Minified it looks like:</p> <pre><code>add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { // Lets grab the order $order = wc_get_order( $order_id ); // Do whatever else } </code></pre> <p>But doesn't mention AdWords specifically.</p> <p>I know through my own testing, that once we define <code>$order = wc_get_order( $order_id );</code> we can get our variables simply using:</p> <pre><code>$totalValue = $order-&gt;get_total(); $currency = $order-&gt;currency; </code></pre> <p>This would bring about a complete function like so:</p> <pre><code>add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { $order = wc_get_order( $order_id ); $totalValue = $order-&gt;get_total(); $currency = $order-&gt;currency; ?&gt; &lt;!-- Google Code for Purchase Conversion Page --&gt; &lt;script type="text/javascript"&gt; /* &lt;![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (&lt;?php echo $totalValue ?&gt;) { var google_conversion_value = &lt;?php echo $totalValue ?&gt;; var google_conversion_currency = &lt;?php echo $currency ?&gt;; } var google_remarketing_only = false; /* ]]&gt; */ &lt;/script&gt; &lt;script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"&gt; &lt;/script&gt; &lt;noscript&gt; &lt;div style="display:inline;"&gt; &lt;img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= &lt;?php echo $totalValue ?&gt;&amp;amp;currency_code=&lt;?php echo $currency ?&gt; &amp;amp;label=xxxxXXx1xXXX123X1xX&amp;amp;guid=ON&amp;amp;script=0"&gt; &lt;/div&gt; &lt;/noscript&gt; &lt;?php } </code></pre> <p>But does not allow us to put it at the end of the <code>&lt;/body&gt;</code> as the AdWords Documentation states.</p> <p>I can't find any information on Transaction Specific values like this in WooCommerce for AdWords, at least nothing definite. There are plenty of plug-ins but they all seem a bit overkill (correct me if I'm wrong) if it's as simple as adding a function perhaps such as the one above.</p> <p>My Questions Are:</p> <ul> <li>Would the above function work just fine regardless?</li> <li>Is there anyway to place the function directly directly above the <code>&lt;/body&gt;</code> as Google suggests?</li> <li>Is there anything else I might be missing here for a proper configuration?</li> </ul>
[ { "answer_id": 274955, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": false, "text": "<p>From the documentation you cited for AdWords: \"When inserting the tag, you'll place it on the static portion of the page, found within the section.\" It doesn't state it <strong><em>must</em></strong> be directly above the closing body tag, and is just providing example code for different common languages. It's a common thought since Google used to recommend Google Analytics scripts to be placed directly above the closing body tag, but for those it's recommended to be placed in the head now. So yes, what you have should work!</p>\n\n<p>In terms of things you might be missing? Well there's quite a bit overall that could happen from point A to point B in a user's journey - but that's kinda one of the points of using a plugin. Plugins aren't necessarily huge overhead if they focus on doing one thing and doing it right.</p>\n\n<p>Maybe as the admin or developer on the site, you don't want to have your tests through the system tracked. Throwing your code in there you'd have to include some additional logic to handle that.</p>\n\n<p>Failed payments and duplicate transactions definitely occur on online shops frequently, so you don't want to have those tracked in those circumstances as well.</p>\n\n<p>As you stumble across those circumstances over time, you end up writing up more code to handle them when you could have saved yourself a lot of worry and effort when things go wrong by just using proven working solutions!</p>\n" }, { "answer_id": 275135, "author": "alev", "author_id": 68337, "author_profile": "https://wordpress.stackexchange.com/users/68337", "pm_score": 3, "selected": true, "text": "<p>As the developer of the <a href=\"https://wordpress.org/plugins/woocommerce-google-adwords-conversion-tracking-tag/\" rel=\"nofollow noreferrer\">WooCommerce AdWords Conversion Tracking</a> plugin I can give you a few answers to your questions plus some reasons to use a plugin or ours in particular. </p>\n\n<p>Answers to your questions:</p>\n\n<ol>\n<li><p>Your function probably will be impaired or not working at all. The reason is, that WordPress filters out the CDATA tags automatically (everything within the content part that is between <code>&lt;body&gt;&lt;/body&gt;</code>). And you can't do anything about it. The filter can't be turned off. It is a bug that has been reported long time ago: <a href=\"http://core.trac.wordpress.org/ticket/3670\" rel=\"nofollow noreferrer\">http://core.trac.wordpress.org/ticket/3670</a> \nThere is an experimental workaround, but it likely will not work\nwith all themes.</p></li>\n<li><p>In theory yes. But Googles instruction is more of a recommendation. The tag will work regardless. If you put it in the header, or footer or directly after the tag, it doesn't really matter. And it is a quite difficult task to position it so exactly using WordPress if you don't want to edit your theme template files. </p></li>\n<li><p>Yes. You are missing: Deduplication, suppression of tracking for failed payments, tax and shipment exclusion, avoid tracking of admins and shop managers to start with. </p></li>\n</ol>\n\n<p>Deduplication: If the visitor reloads the thankyou page for whatever reason, the order will be tracked twice (or even more times).</p>\n\n<p>Failed payments: If a payment fails the thankyou page will still be triggered and thus your tracking code. </p>\n\n<p>Tax and shipment: Generally you don't want to track shipment and tax, just the product price. To get the value without tax and shipment you'll have to use get_subtotal().</p>\n\n<p>In our plugin we have solutions for all issues mentioned above. And we are working on even more interesting functions. </p>\n\n<p>In general plugins can be a good thing if they go beyond just including simple functions, use best practices to avoid performance drag and keep the installations safe.</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102212/" ]
The AdWords Documentation on how to [Track transaction-specific conversion values](https://support.google.com/adwords/answer/6095947?hl=en) states a PHP code as such: ``` <!-- Google Code for Purchase Conversion Page --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (<? echo $totalValue ?>) { var google_conversion_value = <? echo $totalValue ?>; var google_conversion_currency = <? echo $currency ?>; } var google_remarketing_only = false; /* ]]> */ </script> <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= <? echo $totalValue ?>&amp;currency_code=<? echo $currency ?> &amp;label=xxxxXXx1xXXX123X1xX&amp;guid=ON&amp;script=0"> </div> </noscript> </body> ``` This indicates to me two things: 1. We need to put the total order value in a `$totalValue` variable and the currency value into `$currency`. 2. It should be placed at the end of the `</body>` on the page. Aside from creating your own custom 'Thank You' page on Order Completion and adding it where you want in a custom page template, what's the best way to hook onto the default 'Thank You' page? The WooCommerce Documentation has something on [Custom tracking code for the thanks page](https://docs.woocommerce.com/document/custom-tracking-code-for-the-thanks-page/) that just simply hooks onto `woocommerce_thankyou`. Minified it looks like: ``` add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { // Lets grab the order $order = wc_get_order( $order_id ); // Do whatever else } ``` But doesn't mention AdWords specifically. I know through my own testing, that once we define `$order = wc_get_order( $order_id );` we can get our variables simply using: ``` $totalValue = $order->get_total(); $currency = $order->currency; ``` This would bring about a complete function like so: ``` add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { $order = wc_get_order( $order_id ); $totalValue = $order->get_total(); $currency = $order->currency; ?> <!-- Google Code for Purchase Conversion Page --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (<?php echo $totalValue ?>) { var google_conversion_value = <?php echo $totalValue ?>; var google_conversion_currency = <?php echo $currency ?>; } var google_remarketing_only = false; /* ]]> */ </script> <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= <?php echo $totalValue ?>&amp;currency_code=<?php echo $currency ?> &amp;label=xxxxXXx1xXXX123X1xX&amp;guid=ON&amp;script=0"> </div> </noscript> <?php } ``` But does not allow us to put it at the end of the `</body>` as the AdWords Documentation states. I can't find any information on Transaction Specific values like this in WooCommerce for AdWords, at least nothing definite. There are plenty of plug-ins but they all seem a bit overkill (correct me if I'm wrong) if it's as simple as adding a function perhaps such as the one above. My Questions Are: * Would the above function work just fine regardless? * Is there anyway to place the function directly directly above the `</body>` as Google suggests? * Is there anything else I might be missing here for a proper configuration?
As the developer of the [WooCommerce AdWords Conversion Tracking](https://wordpress.org/plugins/woocommerce-google-adwords-conversion-tracking-tag/) plugin I can give you a few answers to your questions plus some reasons to use a plugin or ours in particular. Answers to your questions: 1. Your function probably will be impaired or not working at all. The reason is, that WordPress filters out the CDATA tags automatically (everything within the content part that is between `<body></body>`). And you can't do anything about it. The filter can't be turned off. It is a bug that has been reported long time ago: <http://core.trac.wordpress.org/ticket/3670> There is an experimental workaround, but it likely will not work with all themes. 2. In theory yes. But Googles instruction is more of a recommendation. The tag will work regardless. If you put it in the header, or footer or directly after the tag, it doesn't really matter. And it is a quite difficult task to position it so exactly using WordPress if you don't want to edit your theme template files. 3. Yes. You are missing: Deduplication, suppression of tracking for failed payments, tax and shipment exclusion, avoid tracking of admins and shop managers to start with. Deduplication: If the visitor reloads the thankyou page for whatever reason, the order will be tracked twice (or even more times). Failed payments: If a payment fails the thankyou page will still be triggered and thus your tracking code. Tax and shipment: Generally you don't want to track shipment and tax, just the product price. To get the value without tax and shipment you'll have to use get\_subtotal(). In our plugin we have solutions for all issues mentioned above. And we are working on even more interesting functions. In general plugins can be a good thing if they go beyond just including simple functions, use best practices to avoid performance drag and keep the installations safe.
274,948
<p>WordPress Devs. I am new to WordPress and Web development. So far WordPress Rest API v2 works well. I was writing a custom API/route/endpoint for my project using the following function. </p> <pre><code> get_post($postId); </code></pre> <p>Here the keys that are return as a response are mainly <em>ID, post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, comment_status.</em></p> <p>However, the keys obtain from <a href="http://techdevfan.com/wp-json/wp/v2/posts" rel="nofollow noreferrer">http://techdevfan.com/wp-json/wp/v2/posts</a> are different from the custom API post object mainly <em>id date, date_gmt, guid, modified, status, link, title.</em></p> <p>There is completely no problem in serializing both the response. I just want to know is there any alternative to such problem so that there is no ambiguity in the keys for the two cases other than renaming the keys in $post object of a custom endpoint. </p>
[ { "answer_id": 274955, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": false, "text": "<p>From the documentation you cited for AdWords: \"When inserting the tag, you'll place it on the static portion of the page, found within the section.\" It doesn't state it <strong><em>must</em></strong> be directly above the closing body tag, and is just providing example code for different common languages. It's a common thought since Google used to recommend Google Analytics scripts to be placed directly above the closing body tag, but for those it's recommended to be placed in the head now. So yes, what you have should work!</p>\n\n<p>In terms of things you might be missing? Well there's quite a bit overall that could happen from point A to point B in a user's journey - but that's kinda one of the points of using a plugin. Plugins aren't necessarily huge overhead if they focus on doing one thing and doing it right.</p>\n\n<p>Maybe as the admin or developer on the site, you don't want to have your tests through the system tracked. Throwing your code in there you'd have to include some additional logic to handle that.</p>\n\n<p>Failed payments and duplicate transactions definitely occur on online shops frequently, so you don't want to have those tracked in those circumstances as well.</p>\n\n<p>As you stumble across those circumstances over time, you end up writing up more code to handle them when you could have saved yourself a lot of worry and effort when things go wrong by just using proven working solutions!</p>\n" }, { "answer_id": 275135, "author": "alev", "author_id": 68337, "author_profile": "https://wordpress.stackexchange.com/users/68337", "pm_score": 3, "selected": true, "text": "<p>As the developer of the <a href=\"https://wordpress.org/plugins/woocommerce-google-adwords-conversion-tracking-tag/\" rel=\"nofollow noreferrer\">WooCommerce AdWords Conversion Tracking</a> plugin I can give you a few answers to your questions plus some reasons to use a plugin or ours in particular. </p>\n\n<p>Answers to your questions:</p>\n\n<ol>\n<li><p>Your function probably will be impaired or not working at all. The reason is, that WordPress filters out the CDATA tags automatically (everything within the content part that is between <code>&lt;body&gt;&lt;/body&gt;</code>). And you can't do anything about it. The filter can't be turned off. It is a bug that has been reported long time ago: <a href=\"http://core.trac.wordpress.org/ticket/3670\" rel=\"nofollow noreferrer\">http://core.trac.wordpress.org/ticket/3670</a> \nThere is an experimental workaround, but it likely will not work\nwith all themes.</p></li>\n<li><p>In theory yes. But Googles instruction is more of a recommendation. The tag will work regardless. If you put it in the header, or footer or directly after the tag, it doesn't really matter. And it is a quite difficult task to position it so exactly using WordPress if you don't want to edit your theme template files. </p></li>\n<li><p>Yes. You are missing: Deduplication, suppression of tracking for failed payments, tax and shipment exclusion, avoid tracking of admins and shop managers to start with. </p></li>\n</ol>\n\n<p>Deduplication: If the visitor reloads the thankyou page for whatever reason, the order will be tracked twice (or even more times).</p>\n\n<p>Failed payments: If a payment fails the thankyou page will still be triggered and thus your tracking code. </p>\n\n<p>Tax and shipment: Generally you don't want to track shipment and tax, just the product price. To get the value without tax and shipment you'll have to use get_subtotal().</p>\n\n<p>In our plugin we have solutions for all issues mentioned above. And we are working on even more interesting functions. </p>\n\n<p>In general plugins can be a good thing if they go beyond just including simple functions, use best practices to avoid performance drag and keep the installations safe.</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274948", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125779/" ]
WordPress Devs. I am new to WordPress and Web development. So far WordPress Rest API v2 works well. I was writing a custom API/route/endpoint for my project using the following function. ``` get_post($postId); ``` Here the keys that are return as a response are mainly *ID, post\_author, post\_date, post\_date\_gmt, post\_content, post\_title, post\_excerpt, post\_status, comment\_status.* However, the keys obtain from <http://techdevfan.com/wp-json/wp/v2/posts> are different from the custom API post object mainly *id date, date\_gmt, guid, modified, status, link, title.* There is completely no problem in serializing both the response. I just want to know is there any alternative to such problem so that there is no ambiguity in the keys for the two cases other than renaming the keys in $post object of a custom endpoint.
As the developer of the [WooCommerce AdWords Conversion Tracking](https://wordpress.org/plugins/woocommerce-google-adwords-conversion-tracking-tag/) plugin I can give you a few answers to your questions plus some reasons to use a plugin or ours in particular. Answers to your questions: 1. Your function probably will be impaired or not working at all. The reason is, that WordPress filters out the CDATA tags automatically (everything within the content part that is between `<body></body>`). And you can't do anything about it. The filter can't be turned off. It is a bug that has been reported long time ago: <http://core.trac.wordpress.org/ticket/3670> There is an experimental workaround, but it likely will not work with all themes. 2. In theory yes. But Googles instruction is more of a recommendation. The tag will work regardless. If you put it in the header, or footer or directly after the tag, it doesn't really matter. And it is a quite difficult task to position it so exactly using WordPress if you don't want to edit your theme template files. 3. Yes. You are missing: Deduplication, suppression of tracking for failed payments, tax and shipment exclusion, avoid tracking of admins and shop managers to start with. Deduplication: If the visitor reloads the thankyou page for whatever reason, the order will be tracked twice (or even more times). Failed payments: If a payment fails the thankyou page will still be triggered and thus your tracking code. Tax and shipment: Generally you don't want to track shipment and tax, just the product price. To get the value without tax and shipment you'll have to use get\_subtotal(). In our plugin we have solutions for all issues mentioned above. And we are working on even more interesting functions. In general plugins can be a good thing if they go beyond just including simple functions, use best practices to avoid performance drag and keep the installations safe.
274,984
<p>Wordpress by default already handles the routes to the requested pages but beeing a starter in react and wanting to learn more about it i've found out that you need to create all of your routes. This will extend the app development alot.. What's currently beeing used to overcome this problem?</p>
[ { "answer_id": 275014, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>You basically have to do it yourself. The REST API is only responsible for returning the data, the front end is <em>entirely</em> down to you.</p>\n\n<p>I couldn't find any code that you could just drop into a project to handle routing, but <a href=\"https://lamosty.com/2015/11/10/react-wp-theme-smart-vs-dumb-components-react-router/\" rel=\"nofollow noreferrer\">this article</a> seemed to offer the most detail on doing it with React.</p>\n" }, { "answer_id": 324312, "author": "Dan", "author_id": 145214, "author_profile": "https://wordpress.stackexchange.com/users/145214", "pm_score": 1, "selected": false, "text": "<p>You will need to add <code>react-router-dom</code> with <code>npm</code> or <code>yarn</code>. Once you add those, you will need to import some modules into your React app. You will need <code>BrowserRouter</code>, <code>Route</code>, <code>NavLink</code>, &amp; <code>withRouter</code>. </p>\n\n<p><code>BrowserRouter</code> is to be on the outmost parent Component that manages the history API. Ideally, you would just put your <code>&lt;App /&gt;</code> component inside it in your <code>index.js</code> file, but I think it's simpler to not include 3 separate files in my comment and just wrapped my <code>&lt;App /&gt;</code> response in it here instead.</p>\n\n<p>Any component inside <code>BrowserRouter</code> can use <code>&lt;Route /&gt;</code> and <code>&lt;NavLink /&gt;</code>. <code>Route</code> will trigger based on the request URL and you change the request URL either by manually typing an address or using a <code>&lt;NavLink /&gt;</code> component. At the bottom of the Dropdown component you will see I export the component inside <code>withRouter</code>. This adds useful information to the component's props such as the current url slug.</p>\n\n<p>Here is a simple example.</p>\n\n<p><code>yarn add react-router-dom</code></p>\n\n<pre><code>// App.js\nimport React, {Component} from 'react';\nimport { BrowserRouter, Route } from 'react-router-dom';\nimport axios from 'axios';\n\nimport './App.scss';\nimport {wpAPI} from '../../data/api';\nimport FrontPage from '../../templates/FrontPage';\nimport Header from '../Header/Header';\nimport Post from '../Post/Post';\nimport Sidebar from '../Sidebar/Sidebar';\nimport Footer from '../Footer/Footer';\nimport Spinner from '../Spinner/Spinner';\n\n// Create a React Component\nclass App extends Component {\n state = {\n pages: [],\n posts: [],\n postTypes: [],\n acf: [],\n events: [],\n };\n\n componentDidMount() {\n var keys = Object.keys(this.state);\n\n for ( var i = 0; i &lt; keys.length; i++){\n this.getPosts(keys[i]);\n }\n }\n\n renderContent() {\n if ( this.state.pages ) {\n const {pages} = this.state;\n\n return (\n // Outermost element, contains single root child element.\n &lt;BrowserRouter&gt;\n &lt;section id=\"app\" className=\"animated fadeIn\"&gt;\n &lt;Header /&gt;\n &lt;main&gt;\n // Path = Url after domain &amp; protocal\n // Use render prop to pass props to component, else use component prop ex. component={FrontPage}\n &lt;Route path=\"/\" exact render={(props) =&gt; &lt;FrontPage {...props} pages={ pages } /&gt; } /&gt;\n &lt;Route path=\"/about\" exact render={(props) =&gt; &lt;Post {...props} post={ this.state.pages[3] } /&gt; } /&gt;\n &lt;/main&gt;\n &lt;Sidebar /&gt;\n &lt;Footer /&gt;\n &lt;/section&gt;\n &lt;/BrowserRouter&gt;\n )\n }\n\n return &lt;Spinner message='loading...' /&gt;;\n }\n\n render() {\n return this.renderContent();\n }\n\n /**\n * Takes a post type, builds post type as array of post json in state\n *\n * @param {[string]} type [Post Type]\n */\n getPosts = async (type) =&gt; {\n const response = await axios.get(wpAPI[type]);\n\n this.setState({[type]: response.data})\n }\n};\n\nexport default App;\n</code></pre>\n\n<p>.</p>\n\n<pre><code>// Menu.js\nimport React, {Component} from 'react';\nimport { library } from '@fortawesome/fontawesome-svg-core';\nimport { faChevronDown, faChevronUp } from \"@fortawesome/free-solid-svg-icons\";\nimport { NavLink, withRouter } from 'react-router-dom';\nimport './Dropdown.scss';\n\nlibrary.add(faChevronDown, faChevronUp);\n\nclass Dropdown extends Component {\n constructor(props){\n super(props)\n\n const {title, list, to} = props;\n\n this.state = {\n listOpen: false,\n title: title,\n list: list,\n to: to,\n };\n // console.log(this.state);\n }\n\n handleClickOutside(){\n this.setState({\n listOpen: false\n })\n }\n toggleList(){\n this.setState(prevState =&gt; ({\n listOpen: !prevState.listOpen\n }))\n }\n\n render() {\n const {listOpen, title, list, to} = this.state;\n\n if ( list ) {\n return(\n &lt;div className=\"dropdown dropdown__wrapper\"&gt;\n &lt;header className=\"dropdown__header\" onClick={() =&gt; this.toggleList()}&gt;\n &lt;div className=\"dropdown__title\"&gt;{title}&lt;/div&gt;\n {listOpen\n ? &lt;i className=\"fas fa-chevron-up\"&gt;&lt;/i&gt;\n : &lt;i className=\"fas fa-chevron-down\"&gt;&lt;/i&gt;\n }\n &lt;/header&gt;\n {listOpen &amp;&amp; &lt;ul className=\"dropdown__list\"&gt;\n {list.map((item) =&gt; (\n &lt;NavLink className=\"dropdown__item\" key={item.id} to={item.to}&gt;{item.title}&lt;/NavLink&gt;\n ))}\n &lt;/ul&gt;}\n &lt;/div&gt;\n );\n }\n\n return(\n &lt;div className=\"dropdown dropdown__wrapper\"&gt;\n &lt;div className=\"dropdown__header\" onClick={() =&gt; this.toggleList()}&gt;\n &lt;NavLink className=\"dropdown__title\" to={to}&gt;{title}&lt;/NavLink&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n );\n }\n}\n\nexport default withRouter(Dropdown);\n</code></pre>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274984", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107897/" ]
Wordpress by default already handles the routes to the requested pages but beeing a starter in react and wanting to learn more about it i've found out that you need to create all of your routes. This will extend the app development alot.. What's currently beeing used to overcome this problem?
You will need to add `react-router-dom` with `npm` or `yarn`. Once you add those, you will need to import some modules into your React app. You will need `BrowserRouter`, `Route`, `NavLink`, & `withRouter`. `BrowserRouter` is to be on the outmost parent Component that manages the history API. Ideally, you would just put your `<App />` component inside it in your `index.js` file, but I think it's simpler to not include 3 separate files in my comment and just wrapped my `<App />` response in it here instead. Any component inside `BrowserRouter` can use `<Route />` and `<NavLink />`. `Route` will trigger based on the request URL and you change the request URL either by manually typing an address or using a `<NavLink />` component. At the bottom of the Dropdown component you will see I export the component inside `withRouter`. This adds useful information to the component's props such as the current url slug. Here is a simple example. `yarn add react-router-dom` ``` // App.js import React, {Component} from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import axios from 'axios'; import './App.scss'; import {wpAPI} from '../../data/api'; import FrontPage from '../../templates/FrontPage'; import Header from '../Header/Header'; import Post from '../Post/Post'; import Sidebar from '../Sidebar/Sidebar'; import Footer from '../Footer/Footer'; import Spinner from '../Spinner/Spinner'; // Create a React Component class App extends Component { state = { pages: [], posts: [], postTypes: [], acf: [], events: [], }; componentDidMount() { var keys = Object.keys(this.state); for ( var i = 0; i < keys.length; i++){ this.getPosts(keys[i]); } } renderContent() { if ( this.state.pages ) { const {pages} = this.state; return ( // Outermost element, contains single root child element. <BrowserRouter> <section id="app" className="animated fadeIn"> <Header /> <main> // Path = Url after domain & protocal // Use render prop to pass props to component, else use component prop ex. component={FrontPage} <Route path="/" exact render={(props) => <FrontPage {...props} pages={ pages } /> } /> <Route path="/about" exact render={(props) => <Post {...props} post={ this.state.pages[3] } /> } /> </main> <Sidebar /> <Footer /> </section> </BrowserRouter> ) } return <Spinner message='loading...' />; } render() { return this.renderContent(); } /** * Takes a post type, builds post type as array of post json in state * * @param {[string]} type [Post Type] */ getPosts = async (type) => { const response = await axios.get(wpAPI[type]); this.setState({[type]: response.data}) } }; export default App; ``` . ``` // Menu.js import React, {Component} from 'react'; import { library } from '@fortawesome/fontawesome-svg-core'; import { faChevronDown, faChevronUp } from "@fortawesome/free-solid-svg-icons"; import { NavLink, withRouter } from 'react-router-dom'; import './Dropdown.scss'; library.add(faChevronDown, faChevronUp); class Dropdown extends Component { constructor(props){ super(props) const {title, list, to} = props; this.state = { listOpen: false, title: title, list: list, to: to, }; // console.log(this.state); } handleClickOutside(){ this.setState({ listOpen: false }) } toggleList(){ this.setState(prevState => ({ listOpen: !prevState.listOpen })) } render() { const {listOpen, title, list, to} = this.state; if ( list ) { return( <div className="dropdown dropdown__wrapper"> <header className="dropdown__header" onClick={() => this.toggleList()}> <div className="dropdown__title">{title}</div> {listOpen ? <i className="fas fa-chevron-up"></i> : <i className="fas fa-chevron-down"></i> } </header> {listOpen && <ul className="dropdown__list"> {list.map((item) => ( <NavLink className="dropdown__item" key={item.id} to={item.to}>{item.title}</NavLink> ))} </ul>} </div> ); } return( <div className="dropdown dropdown__wrapper"> <div className="dropdown__header" onClick={() => this.toggleList()}> <NavLink className="dropdown__title" to={to}>{title}</NavLink> </div> </div> ); } } export default withRouter(Dropdown); ```
274,986
<p>I needed to translate strings on another language than the current $locale, so I need to change the locale and restore it later, and I really couldn't repeat all the code for the 30++ strings I had to translate.</p> <p>So I ended up with this function:</p> <pre><code>function __2($string, $textdomain, $locale){ global $l10n; if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain]; load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo'); $translation = __($string,$textdomain); if(isset($bkup)) $l10n[$textdomain] = $backup; return $translation; } </code></pre> <p>Now, as per this famous article, I really shouldn't have coded that function :</p> <p><a href="http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/" rel="nofollow noreferrer">http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/</a></p> <p>...But it simply works. So my question is: is it really ALWAYS wrong to pass variabled to l10n functions? An eventually why? And why shouldn't I use my function if it just works?</p>
[ { "answer_id": 274992, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>No it does not work, people that will need to translate the string will not be able to use the automated tools they usually use to extract the strings that need translation.</p>\n\n<p>And yes, it is always bad.</p>\n" }, { "answer_id": 275007, "author": "Luca Reghellin", "author_id": 10381, "author_profile": "https://wordpress.stackexchange.com/users/10381", "pm_score": -1, "selected": true, "text": "<p>The answer is: sometimes. As long as you know what you are doing, there are no problems in terms of bugs. There can be situations where this is possible and safe, and other where it can be necessary or extremely useful.</p>\n\n<p>To complete and share the code above, I add the following:</p>\n\n<pre><code>function _e2($string, $textdomain, $locale){\n echo __2($string, $textdomain, $locale);\n}\n\n// example\n\n_e2('hello','stratboy','it_IT');\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Some bonus code can be found here:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/231685/how-to-get-a-traslated-string-from-a-language-other-than-the-current-one/274985#274985\">How to get a traslated string from a language other than the current one?</a></p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10381/" ]
I needed to translate strings on another language than the current $locale, so I need to change the locale and restore it later, and I really couldn't repeat all the code for the 30++ strings I had to translate. So I ended up with this function: ``` function __2($string, $textdomain, $locale){ global $l10n; if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain]; load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo'); $translation = __($string,$textdomain); if(isset($bkup)) $l10n[$textdomain] = $backup; return $translation; } ``` Now, as per this famous article, I really shouldn't have coded that function : <http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/> ...But it simply works. So my question is: is it really ALWAYS wrong to pass variabled to l10n functions? An eventually why? And why shouldn't I use my function if it just works?
The answer is: sometimes. As long as you know what you are doing, there are no problems in terms of bugs. There can be situations where this is possible and safe, and other where it can be necessary or extremely useful. To complete and share the code above, I add the following: ``` function _e2($string, $textdomain, $locale){ echo __2($string, $textdomain, $locale); } // example _e2('hello','stratboy','it_IT'); ``` **UPDATE:** Some bonus code can be found here: [How to get a traslated string from a language other than the current one?](https://wordpress.stackexchange.com/questions/231685/how-to-get-a-traslated-string-from-a-language-other-than-the-current-one/274985#274985)
274,997
<p>I am using Woocommerce plugin for my custom product .and I am stuck with a situation .</p> <p>Does Woo commerce provide any hook or filter when refund is done through admin panel and refund will be manually.<a href="https://i.stack.imgur.com/z8mcA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/z8mcA.png" alt="For More details please see attached image "></a> </p>
[ { "answer_id": 296779, "author": "Tech Dog", "author_id": 138476, "author_profile": "https://wordpress.stackexchange.com/users/138476", "pm_score": 4, "selected": false, "text": "<p>Although this answer is little late but anyone else may get benefit from it. The <code>woocommerce_order_refunded</code> hook is called when an order is refunded. Use the following example:</p>\n\n<pre><code>// add the action \nadd_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); \n// Do the magic\nfunction action_woocommerce_order_refunded( $order_id, $refund_id ) \n{ \n // Your code here\n}\n</code></pre>\n" }, { "answer_id": 398394, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>My answer is for emails or when refunds are done through the payment gateway but it might help someone coming across this. So in addition to <a href=\"https://wordpress.stackexchange.com/a/296779/76433\">Tech Dog's answer</a> You can use a few other hooks specifically for partial refunds: <code>woocommerce_order_partially_refunded</code> and for full refunds: <code>woocommerce_order_fully_refunded</code></p>\n<p>These hooks can be seen <a href=\"https://github.com/woocommerce/woocommerce/blob/5.9.0/includes/wc-order-functions.php#L614-L616\" rel=\"nofollow noreferrer\">here</a> (I copied the lines at version 5.9 of WooCommerce, so depending on when someone is reading this the hooks might be on different lines in the latest version)</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98958/" ]
I am using Woocommerce plugin for my custom product .and I am stuck with a situation . Does Woo commerce provide any hook or filter when refund is done through admin panel and refund will be manually.[![For More details please see attached image ](https://i.stack.imgur.com/z8mcA.png)](https://i.stack.imgur.com/z8mcA.png)
Although this answer is little late but anyone else may get benefit from it. The `woocommerce_order_refunded` hook is called when an order is refunded. Use the following example: ``` // add the action add_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); // Do the magic function action_woocommerce_order_refunded( $order_id, $refund_id ) { // Your code here } ```
275,010
<ol> <li>On navigation, can a parent-grandchild menu appear? That is, are we able to pick and choose which categories we would like to suppress?</li> </ol> <p>Example: if taxonomy shows: Food>Fruit>Citrus>Oranges>Types of oranges Can we design the navigation to show: Fruit>Oranges>Types of oranges</p> <ol start="2"> <li><p>How many subcategories are possible?</p></li> <li><p>On navigation, can we rename categories on the front-end but keep a different taxonomy on the back end?</p></li> </ol> <p>Example: if taxonomy is: Food>Fruit>Citrus>Oranges>Types of oranges Can we actually have the users see these words instead (but they should experience navigation per the taxonomy?) Yummy things>Fruitilicious>Citrus</p>
[ { "answer_id": 296779, "author": "Tech Dog", "author_id": 138476, "author_profile": "https://wordpress.stackexchange.com/users/138476", "pm_score": 4, "selected": false, "text": "<p>Although this answer is little late but anyone else may get benefit from it. The <code>woocommerce_order_refunded</code> hook is called when an order is refunded. Use the following example:</p>\n\n<pre><code>// add the action \nadd_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); \n// Do the magic\nfunction action_woocommerce_order_refunded( $order_id, $refund_id ) \n{ \n // Your code here\n}\n</code></pre>\n" }, { "answer_id": 398394, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>My answer is for emails or when refunds are done through the payment gateway but it might help someone coming across this. So in addition to <a href=\"https://wordpress.stackexchange.com/a/296779/76433\">Tech Dog's answer</a> You can use a few other hooks specifically for partial refunds: <code>woocommerce_order_partially_refunded</code> and for full refunds: <code>woocommerce_order_fully_refunded</code></p>\n<p>These hooks can be seen <a href=\"https://github.com/woocommerce/woocommerce/blob/5.9.0/includes/wc-order-functions.php#L614-L616\" rel=\"nofollow noreferrer\">here</a> (I copied the lines at version 5.9 of WooCommerce, so depending on when someone is reading this the hooks might be on different lines in the latest version)</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275010", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124756/" ]
1. On navigation, can a parent-grandchild menu appear? That is, are we able to pick and choose which categories we would like to suppress? Example: if taxonomy shows: Food>Fruit>Citrus>Oranges>Types of oranges Can we design the navigation to show: Fruit>Oranges>Types of oranges 2. How many subcategories are possible? 3. On navigation, can we rename categories on the front-end but keep a different taxonomy on the back end? Example: if taxonomy is: Food>Fruit>Citrus>Oranges>Types of oranges Can we actually have the users see these words instead (but they should experience navigation per the taxonomy?) Yummy things>Fruitilicious>Citrus
Although this answer is little late but anyone else may get benefit from it. The `woocommerce_order_refunded` hook is called when an order is refunded. Use the following example: ``` // add the action add_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); // Do the magic function action_woocommerce_order_refunded( $order_id, $refund_id ) { // Your code here } ```
275,018
<p>In my situation, style.css file has just package information and a comment as: All css files are placed in /css/ folder.</p> <p>In the css folder, I see a bunch of different styles and I don't exactly know which one controls what! </p> <p>Any suggestions on overriding the CSS rules from a child theme? </p>
[ { "answer_id": 296779, "author": "Tech Dog", "author_id": 138476, "author_profile": "https://wordpress.stackexchange.com/users/138476", "pm_score": 4, "selected": false, "text": "<p>Although this answer is little late but anyone else may get benefit from it. The <code>woocommerce_order_refunded</code> hook is called when an order is refunded. Use the following example:</p>\n\n<pre><code>// add the action \nadd_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); \n// Do the magic\nfunction action_woocommerce_order_refunded( $order_id, $refund_id ) \n{ \n // Your code here\n}\n</code></pre>\n" }, { "answer_id": 398394, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>My answer is for emails or when refunds are done through the payment gateway but it might help someone coming across this. So in addition to <a href=\"https://wordpress.stackexchange.com/a/296779/76433\">Tech Dog's answer</a> You can use a few other hooks specifically for partial refunds: <code>woocommerce_order_partially_refunded</code> and for full refunds: <code>woocommerce_order_fully_refunded</code></p>\n<p>These hooks can be seen <a href=\"https://github.com/woocommerce/woocommerce/blob/5.9.0/includes/wc-order-functions.php#L614-L616\" rel=\"nofollow noreferrer\">here</a> (I copied the lines at version 5.9 of WooCommerce, so depending on when someone is reading this the hooks might be on different lines in the latest version)</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275018", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124648/" ]
In my situation, style.css file has just package information and a comment as: All css files are placed in /css/ folder. In the css folder, I see a bunch of different styles and I don't exactly know which one controls what! Any suggestions on overriding the CSS rules from a child theme?
Although this answer is little late but anyone else may get benefit from it. The `woocommerce_order_refunded` hook is called when an order is refunded. Use the following example: ``` // add the action add_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); // Do the magic function action_woocommerce_order_refunded( $order_id, $refund_id ) { // Your code here } ```
275,023
<p>I have made a plugin that uses a CPT and a few metadatas. The plugin comes in two versions A and B.</p> <p>Version A has one post meta less then version B called 'score'. When users update the plugin from A to B I need the score meta to be created for all custom posts for version B to work properly.</p> <p>This is the insert query I have used:</p> <pre><code>global $wpdb; $wpdb-&gt;query( " INSERT INTO $wpdb-&gt;postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb-&gt;posts AS p WHERE p.post_type = 'my_cpt' " ); </code></pre> <p>This query works to add the new metadata but will create duplicates if runned multiple times. What should I do to make the query add the metadata only if it does not exist already?</p> <p>Thanks for any possible solution.</p>
[ { "answer_id": 275025, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>You only want to <code>INSERT</code> for posts, that do not have this postmeta yet. So you need to change your <code>SELECT</code> to only get those.</p>\n\n<p>I just tried a couple of things and it seems tricky. What did work for me - but is an expensive query - is the following. Since this will only be run on plugin activation, the performance shouldn't be too much of a problem.</p>\n\n<pre><code>INSERT INTO $wpdb-&gt;postmeta (post_id,meta_key,meta_value)\nSELECT p.ID, 'score' AS meta_key, 0 AS meta_value\nFROM $wpdb-&gt;posts AS p\nWHERE p.post_type = 'my_cpt'\nAND WHERE p.ID NOT IN (\n SELECT $wpdb-&gt;posts AS p2\n INNER JOIN $wpdb-&gt;postmeta AS pm\n ON pm.post_id = p2.ID\n WHERE pm.meta_key = 'score'\n)\n</code></pre>\n" }, { "answer_id": 276081, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 2, "selected": true, "text": "<p>To anyone interested this is the query that worked for me:</p>\n\n<pre><code>INSERT INTO $wpdb-&gt;postmeta (post_id,meta_key,meta_value)\nSELECT p.ID, 'score' AS meta_key, 0 AS meta_value\nFROM $wpdb-&gt;posts AS p\nWHERE p.post_type = 'my_cpt'\nAND p.ID NOT IN (\n SELECT p2.ID \n FROM $wpdb-&gt;posts AS p2\n INNER JOIN $wpdb-&gt;postmeta AS pm\n ON pm.post_id = p2.ID\n WHERE pm.meta_key = 'score'\n)\n</code></pre>\n\n<p>But after reading <a href=\"https://www.percona.com/blog/2010/10/25/mysql-limitations-part-3-subqueries/\" rel=\"nofollow noreferrer\">this article</a> I preferred to split the query in two for better performance:</p>\n\n<pre><code>global $wpdb;\n\n//Get all posts which already have the metadata\n$not_in = $wpdb-&gt;get_results( \n \"\n SELECT p.ID\n FROM $wpdb-&gt;posts AS p\n INNER JOIN $wpdb-&gt;postmeta AS pm\n ON pm.post_id = p.ID\n WHERE pm.meta_key = 'score'\n AND p.post_type = 'my-cpt'\n AND p.post_status NOT IN ('draft,auto-draft')\",\n ARRAY_A\n);\n\n//Make results into string\n$not_in = ! empty($not_in) ? implode( ',', array_column( $not_in, 'ID' ) ) : '';\n\n//Insert new metadata\n$wpdb-&gt;query(\n \"\n INSERT INTO $wpdb-&gt;postmeta (post_id,meta_key,meta_value)\n SELECT p.ID, 'score' AS meta_key, 0 AS meta_value\n FROM $wpdb-&gt;posts AS p\n WHERE p.post_type = 'my-cpt'\n AND p.ID NOT IN ( $not_in )\n \"\n);\n</code></pre>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275023", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124757/" ]
I have made a plugin that uses a CPT and a few metadatas. The plugin comes in two versions A and B. Version A has one post meta less then version B called 'score'. When users update the plugin from A to B I need the score meta to be created for all custom posts for version B to work properly. This is the insert query I have used: ``` global $wpdb; $wpdb->query( " INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb->posts AS p WHERE p.post_type = 'my_cpt' " ); ``` This query works to add the new metadata but will create duplicates if runned multiple times. What should I do to make the query add the metadata only if it does not exist already? Thanks for any possible solution.
To anyone interested this is the query that worked for me: ``` INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb->posts AS p WHERE p.post_type = 'my_cpt' AND p.ID NOT IN ( SELECT p2.ID FROM $wpdb->posts AS p2 INNER JOIN $wpdb->postmeta AS pm ON pm.post_id = p2.ID WHERE pm.meta_key = 'score' ) ``` But after reading [this article](https://www.percona.com/blog/2010/10/25/mysql-limitations-part-3-subqueries/) I preferred to split the query in two for better performance: ``` global $wpdb; //Get all posts which already have the metadata $not_in = $wpdb->get_results( " SELECT p.ID FROM $wpdb->posts AS p INNER JOIN $wpdb->postmeta AS pm ON pm.post_id = p.ID WHERE pm.meta_key = 'score' AND p.post_type = 'my-cpt' AND p.post_status NOT IN ('draft,auto-draft')", ARRAY_A ); //Make results into string $not_in = ! empty($not_in) ? implode( ',', array_column( $not_in, 'ID' ) ) : ''; //Insert new metadata $wpdb->query( " INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb->posts AS p WHERE p.post_type = 'my-cpt' AND p.ID NOT IN ( $not_in ) " ); ```
275,030
<p>My theme has a top menu bar with accessibility shortcuts (jump to content, high contrast mode, etc). I need to include a link to an informational page describing the accessibility features available to visitors.</p> <p>This is a project for an University multisite network, with a lot of hosted sites, so I need a solution that doesn't require manually creating the page on each site. I also want to be able to easily update this content on future versions of the theme (i.e., inserting the content in the database of several sites may not be a good idea).</p> <p>I'm considering linking to the site's home page with some URL parameter, e.g. site1.example.com/?info=accessibility and addressing the content in the index.php, but that doesn't look too elegant. </p> <p>Any advice on a cleaner way to implement this?</p> <p>Thanks in advance!</p>
[ { "answer_id": 275044, "author": "Dub Scrib", "author_id": 75797, "author_profile": "https://wordpress.stackexchange.com/users/75797", "pm_score": 0, "selected": false, "text": "<p>If a plugin would work - see the WP Accessibility plugin. In Settings, 'Add Skiplinks' section, there's an option to add your own link (link or container ID). Could point to a central page?</p>\n" }, { "answer_id": 275137, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": true, "text": "<p>I am assuming the following setup from reading your question: </p>\n\n<p>site.network.com</p>\n\n<p>site-2.network.com</p>\n\n<p>site-3.network.com </p>\n\n<p>where the main site exists on network.com (i.e. blog id <code>1</code>).\nAll sites (or at least all subdomain sites) share the same theme.</p>\n\n<p>You need to be able to create a single content page and have that content available on all sites, i.e. *.network.com/some-page/</p>\n\n<hr>\n\n<p>The below covers using a page on the main site (id 1) as the content source (allowing you to update/edit that content via the editor), and a template file for a matching page title. </p>\n\n<p>You could include static content the same way. (see <em>Notes on Step 1</em> at the end).</p>\n\n<hr>\n\n<h2>Step 1</h2>\n\n<p>You can add a page template to the theme for a specific page, say, named <em>Accessibility</em> by duplicating the <em>page.php</em> and renaming it <em>page-accessibility.php</em></p>\n\n<h2>Step 2</h2>\n\n<p>In <em>page-accessibility.php</em>, we will remove the normal loop, and replace it with some code to get a different page's content: the <em>Accessibility</em> page from the main site; using <code>switch_to_blog()</code>.</p>\n\n<p>If the main site id is <code>1</code>, the template page <em>page-accessibility.php</em> might look something like this:</p>\n\n<pre><code>get_header(); \n\nswitch_to_blog(1);\n$post = get_page_by_title( 'Accessibility' );\n\nif ($post) {\n $content = do_shortcode( html_entity_decode( $post-&gt;post_content ) );\n}\nrestore_current_blog();\n\n?&gt;\n\n &lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php echo $content; ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n &lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php\nget_sidebar();\nget_footer();\n</code></pre>\n\n<h2> Step 3</h2>\n\n<p>Create an empty page named <em>Accessibility</em> for all sites. Rather than run something that would use <code>switch_to_blog()</code> to create a page for each one, we could instead check for the existence of the page on <code>init</code> of the site, and only create it if it doesn't exist. </p>\n\n<p><em>functions.php of theme</em></p>\n\n<pre><code>add_action( 'init', 'set_default_page' );\n\nfunction set_default_page() {\n\n check_exists_create_page( 'Accessibility' ); //again, checking by title\n}\n\n\nfunction check_exists_create_page( $title ) {\n\n if ( get_page_by_title( $title ) == NULL ) {\n\n $args = array(\n 'post_title' =&gt; $title,\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_type' =&gt; 'page'\n );\n\n wp_insert_post( $args ); \n }\n\n}\n</code></pre>\n\n<hr>\n\n<h2>Notes on Step 1</h2>\n\n<p>You could also use this <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierarchy</a> to include static content. Remove the normal loop, and add your content directly or include another php file, etc. Then skip to Step 3 and create a page with a name that matches the <em>page-{your-page-name}.php</em> pattern for each site.</p>\n\n<h2>Notes on Step 2</h2>\n\n<p>If you are wanting to use a site other than id<code>1</code>, you can always retrieve the id of the site you wish to use via <a href=\"https://codex.wordpress.org/Function_Reference/get_current_blog_id\" rel=\"nofollow noreferrer\"><code>get_current_blog_id()</code></a></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\"><code>get_page_by_title()</code></a> uses title <strong>not</strong> slug. To get a page titled <em>My New Page</em>:</p>\n\n<p><code>get_page_by_title( 'My New Page' )</code></p>\n\n<p>Here I am just linking more info on <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\"><code>do_shortcode()</code></a> and <a href=\"http://php.net/manual/en/function.html-entity-decode.php\" rel=\"nofollow noreferrer\"><code>html_entity_decode()</code></a>.\nAnd for <a href=\"https://codex.wordpress.org/Function_Reference/switch_to_blog\" rel=\"nofollow noreferrer\"><code>switch_to_blog()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/restore_current_blog\" rel=\"nofollow noreferrer\"><code>restore_current_blog()</code></a>.</p>\n\n<h2>Notes on Step 3</h2>\n\n<p>There may be a better hook than <code>init</code>. You could also add a conditional check if you wish to exclude some sites from this page check/creation. See my <a href=\"https://wordpress.stackexchange.com/a/275057/118366\">answer on a different question</a> if you need that.</p>\n\n<p>Be aware during testing that a page in Trash still exists.</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275030", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68849/" ]
My theme has a top menu bar with accessibility shortcuts (jump to content, high contrast mode, etc). I need to include a link to an informational page describing the accessibility features available to visitors. This is a project for an University multisite network, with a lot of hosted sites, so I need a solution that doesn't require manually creating the page on each site. I also want to be able to easily update this content on future versions of the theme (i.e., inserting the content in the database of several sites may not be a good idea). I'm considering linking to the site's home page with some URL parameter, e.g. site1.example.com/?info=accessibility and addressing the content in the index.php, but that doesn't look too elegant. Any advice on a cleaner way to implement this? Thanks in advance!
I am assuming the following setup from reading your question: site.network.com site-2.network.com site-3.network.com where the main site exists on network.com (i.e. blog id `1`). All sites (or at least all subdomain sites) share the same theme. You need to be able to create a single content page and have that content available on all sites, i.e. \*.network.com/some-page/ --- The below covers using a page on the main site (id 1) as the content source (allowing you to update/edit that content via the editor), and a template file for a matching page title. You could include static content the same way. (see *Notes on Step 1* at the end). --- Step 1 ------ You can add a page template to the theme for a specific page, say, named *Accessibility* by duplicating the *page.php* and renaming it *page-accessibility.php* Step 2 ------ In *page-accessibility.php*, we will remove the normal loop, and replace it with some code to get a different page's content: the *Accessibility* page from the main site; using `switch_to_blog()`. If the main site id is `1`, the template page *page-accessibility.php* might look something like this: ``` get_header(); switch_to_blog(1); $post = get_page_by_title( 'Accessibility' ); if ($post) { $content = do_shortcode( html_entity_decode( $post->post_content ) ); } restore_current_blog(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php echo $content; ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); get_footer(); ``` Step 3 ------- Create an empty page named *Accessibility* for all sites. Rather than run something that would use `switch_to_blog()` to create a page for each one, we could instead check for the existence of the page on `init` of the site, and only create it if it doesn't exist. *functions.php of theme* ``` add_action( 'init', 'set_default_page' ); function set_default_page() { check_exists_create_page( 'Accessibility' ); //again, checking by title } function check_exists_create_page( $title ) { if ( get_page_by_title( $title ) == NULL ) { $args = array( 'post_title' => $title, 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'page' ); wp_insert_post( $args ); } } ``` --- Notes on Step 1 --------------- You could also use this [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) to include static content. Remove the normal loop, and add your content directly or include another php file, etc. Then skip to Step 3 and create a page with a name that matches the *page-{your-page-name}.php* pattern for each site. Notes on Step 2 --------------- If you are wanting to use a site other than id`1`, you can always retrieve the id of the site you wish to use via [`get_current_blog_id()`](https://codex.wordpress.org/Function_Reference/get_current_blog_id) [`get_page_by_title()`](https://codex.wordpress.org/Function_Reference/get_page_by_title) uses title **not** slug. To get a page titled *My New Page*: `get_page_by_title( 'My New Page' )` Here I am just linking more info on [`do_shortcode()`](https://developer.wordpress.org/reference/functions/do_shortcode/) and [`html_entity_decode()`](http://php.net/manual/en/function.html-entity-decode.php). And for [`switch_to_blog()`](https://codex.wordpress.org/Function_Reference/switch_to_blog) and [`restore_current_blog()`](https://codex.wordpress.org/Function_Reference/restore_current_blog). Notes on Step 3 --------------- There may be a better hook than `init`. You could also add a conditional check if you wish to exclude some sites from this page check/creation. See my [answer on a different question](https://wordpress.stackexchange.com/a/275057/118366) if you need that. Be aware during testing that a page in Trash still exists.
275,038
<p>After migrating subdomain to new domain, not sure if the subdomain got left over in any of the settings.</p> <p>Where in PHPmyAdmin / SQL database should I find those subdomain urls and update them to the new one?</p> <p>(not even sure if my question makes sense).</p> <p>Any help will appreciated</p>
[ { "answer_id": 275044, "author": "Dub Scrib", "author_id": 75797, "author_profile": "https://wordpress.stackexchange.com/users/75797", "pm_score": 0, "selected": false, "text": "<p>If a plugin would work - see the WP Accessibility plugin. In Settings, 'Add Skiplinks' section, there's an option to add your own link (link or container ID). Could point to a central page?</p>\n" }, { "answer_id": 275137, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": true, "text": "<p>I am assuming the following setup from reading your question: </p>\n\n<p>site.network.com</p>\n\n<p>site-2.network.com</p>\n\n<p>site-3.network.com </p>\n\n<p>where the main site exists on network.com (i.e. blog id <code>1</code>).\nAll sites (or at least all subdomain sites) share the same theme.</p>\n\n<p>You need to be able to create a single content page and have that content available on all sites, i.e. *.network.com/some-page/</p>\n\n<hr>\n\n<p>The below covers using a page on the main site (id 1) as the content source (allowing you to update/edit that content via the editor), and a template file for a matching page title. </p>\n\n<p>You could include static content the same way. (see <em>Notes on Step 1</em> at the end).</p>\n\n<hr>\n\n<h2>Step 1</h2>\n\n<p>You can add a page template to the theme for a specific page, say, named <em>Accessibility</em> by duplicating the <em>page.php</em> and renaming it <em>page-accessibility.php</em></p>\n\n<h2>Step 2</h2>\n\n<p>In <em>page-accessibility.php</em>, we will remove the normal loop, and replace it with some code to get a different page's content: the <em>Accessibility</em> page from the main site; using <code>switch_to_blog()</code>.</p>\n\n<p>If the main site id is <code>1</code>, the template page <em>page-accessibility.php</em> might look something like this:</p>\n\n<pre><code>get_header(); \n\nswitch_to_blog(1);\n$post = get_page_by_title( 'Accessibility' );\n\nif ($post) {\n $content = do_shortcode( html_entity_decode( $post-&gt;post_content ) );\n}\nrestore_current_blog();\n\n?&gt;\n\n &lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php echo $content; ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n &lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php\nget_sidebar();\nget_footer();\n</code></pre>\n\n<h2> Step 3</h2>\n\n<p>Create an empty page named <em>Accessibility</em> for all sites. Rather than run something that would use <code>switch_to_blog()</code> to create a page for each one, we could instead check for the existence of the page on <code>init</code> of the site, and only create it if it doesn't exist. </p>\n\n<p><em>functions.php of theme</em></p>\n\n<pre><code>add_action( 'init', 'set_default_page' );\n\nfunction set_default_page() {\n\n check_exists_create_page( 'Accessibility' ); //again, checking by title\n}\n\n\nfunction check_exists_create_page( $title ) {\n\n if ( get_page_by_title( $title ) == NULL ) {\n\n $args = array(\n 'post_title' =&gt; $title,\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_type' =&gt; 'page'\n );\n\n wp_insert_post( $args ); \n }\n\n}\n</code></pre>\n\n<hr>\n\n<h2>Notes on Step 1</h2>\n\n<p>You could also use this <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierarchy</a> to include static content. Remove the normal loop, and add your content directly or include another php file, etc. Then skip to Step 3 and create a page with a name that matches the <em>page-{your-page-name}.php</em> pattern for each site.</p>\n\n<h2>Notes on Step 2</h2>\n\n<p>If you are wanting to use a site other than id<code>1</code>, you can always retrieve the id of the site you wish to use via <a href=\"https://codex.wordpress.org/Function_Reference/get_current_blog_id\" rel=\"nofollow noreferrer\"><code>get_current_blog_id()</code></a></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\"><code>get_page_by_title()</code></a> uses title <strong>not</strong> slug. To get a page titled <em>My New Page</em>:</p>\n\n<p><code>get_page_by_title( 'My New Page' )</code></p>\n\n<p>Here I am just linking more info on <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\"><code>do_shortcode()</code></a> and <a href=\"http://php.net/manual/en/function.html-entity-decode.php\" rel=\"nofollow noreferrer\"><code>html_entity_decode()</code></a>.\nAnd for <a href=\"https://codex.wordpress.org/Function_Reference/switch_to_blog\" rel=\"nofollow noreferrer\"><code>switch_to_blog()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/restore_current_blog\" rel=\"nofollow noreferrer\"><code>restore_current_blog()</code></a>.</p>\n\n<h2>Notes on Step 3</h2>\n\n<p>There may be a better hook than <code>init</code>. You could also add a conditional check if you wish to exclude some sites from this page check/creation. See my <a href=\"https://wordpress.stackexchange.com/a/275057/118366\">answer on a different question</a> if you need that.</p>\n\n<p>Be aware during testing that a page in Trash still exists.</p>\n" } ]
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124762/" ]
After migrating subdomain to new domain, not sure if the subdomain got left over in any of the settings. Where in PHPmyAdmin / SQL database should I find those subdomain urls and update them to the new one? (not even sure if my question makes sense). Any help will appreciated
I am assuming the following setup from reading your question: site.network.com site-2.network.com site-3.network.com where the main site exists on network.com (i.e. blog id `1`). All sites (or at least all subdomain sites) share the same theme. You need to be able to create a single content page and have that content available on all sites, i.e. \*.network.com/some-page/ --- The below covers using a page on the main site (id 1) as the content source (allowing you to update/edit that content via the editor), and a template file for a matching page title. You could include static content the same way. (see *Notes on Step 1* at the end). --- Step 1 ------ You can add a page template to the theme for a specific page, say, named *Accessibility* by duplicating the *page.php* and renaming it *page-accessibility.php* Step 2 ------ In *page-accessibility.php*, we will remove the normal loop, and replace it with some code to get a different page's content: the *Accessibility* page from the main site; using `switch_to_blog()`. If the main site id is `1`, the template page *page-accessibility.php* might look something like this: ``` get_header(); switch_to_blog(1); $post = get_page_by_title( 'Accessibility' ); if ($post) { $content = do_shortcode( html_entity_decode( $post->post_content ) ); } restore_current_blog(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php echo $content; ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); get_footer(); ``` Step 3 ------- Create an empty page named *Accessibility* for all sites. Rather than run something that would use `switch_to_blog()` to create a page for each one, we could instead check for the existence of the page on `init` of the site, and only create it if it doesn't exist. *functions.php of theme* ``` add_action( 'init', 'set_default_page' ); function set_default_page() { check_exists_create_page( 'Accessibility' ); //again, checking by title } function check_exists_create_page( $title ) { if ( get_page_by_title( $title ) == NULL ) { $args = array( 'post_title' => $title, 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'page' ); wp_insert_post( $args ); } } ``` --- Notes on Step 1 --------------- You could also use this [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) to include static content. Remove the normal loop, and add your content directly or include another php file, etc. Then skip to Step 3 and create a page with a name that matches the *page-{your-page-name}.php* pattern for each site. Notes on Step 2 --------------- If you are wanting to use a site other than id`1`, you can always retrieve the id of the site you wish to use via [`get_current_blog_id()`](https://codex.wordpress.org/Function_Reference/get_current_blog_id) [`get_page_by_title()`](https://codex.wordpress.org/Function_Reference/get_page_by_title) uses title **not** slug. To get a page titled *My New Page*: `get_page_by_title( 'My New Page' )` Here I am just linking more info on [`do_shortcode()`](https://developer.wordpress.org/reference/functions/do_shortcode/) and [`html_entity_decode()`](http://php.net/manual/en/function.html-entity-decode.php). And for [`switch_to_blog()`](https://codex.wordpress.org/Function_Reference/switch_to_blog) and [`restore_current_blog()`](https://codex.wordpress.org/Function_Reference/restore_current_blog). Notes on Step 3 --------------- There may be a better hook than `init`. You could also add a conditional check if you wish to exclude some sites from this page check/creation. See my [answer on a different question](https://wordpress.stackexchange.com/a/275057/118366) if you need that. Be aware during testing that a page in Trash still exists.
275,112
<pre><code>&lt;button name="button" style="margin: 20px 0 0 796px;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" &gt;HAVE A QUESTIONS&lt;/button&gt; </code></pre> <p>i make a button in my custom template page(header.php) but its display also my home page but i want to display only my custom template page.......how do i hide this button in my home page(front page)</p>
[ { "answer_id": 275116, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>It's as simple as doing a conditional and check if you are on home.</p>\n\n<p>What you are looking for is <code>is_page_template( );</code>. Wrap your button inside it as follows:</p>\n\n<pre><code>&lt;?php if( is_page_template( 'your-template-slug.php' ) ){ ?&gt;\n &lt;button name=\"button\" style=\" ... \" value=\"OK\" type=\"button\"&gt;HAVE A QUESTIONS&lt;/button&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 275117, "author": "WendiT", "author_id": 39284, "author_profile": "https://wordpress.stackexchange.com/users/39284", "pm_score": -1, "selected": false, "text": "<p>You can use this in your css file</p>\n\n<pre><code>.home button[type=button] {display:none}\n</code></pre>\n" } ]
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124815/" ]
``` <button name="button" style="margin: 20px 0 0 796px;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" >HAVE A QUESTIONS</button> ``` i make a button in my custom template page(header.php) but its display also my home page but i want to display only my custom template page.......how do i hide this button in my home page(front page)
It's as simple as doing a conditional and check if you are on home. What you are looking for is `is_page_template( );`. Wrap your button inside it as follows: ``` <?php if( is_page_template( 'your-template-slug.php' ) ){ ?> <button name="button" style=" ... " value="OK" type="button">HAVE A QUESTIONS</button> <?php } ?> ```
275,120
<p>I am trying to learn meta's in Wordpress by taking an example of the already existing meta →</p> <pre><code>function cpmb_display_meta_box( $post ) { // Define the nonce for security purposes wp_nonce_field( plugin_basename( __FILE__ ), 'cpmb-nonce-field' ); // Start the HTML string so that all other strings can be concatenated $html = ''; // If the current post has an invalid file type associated with it, // then display an error message. if ( 'invalid-file-type' == get_post_meta( $post-&gt;ID, 'mp3', true ) ) { $html .= '&lt;div id="invalid-file-type" class="error"&gt;'; $html .= '&lt;p&gt;You are trying to upload a file other than an MP3.&lt;/p&gt;'; $html .= '&lt;/div&gt;'; } // Display the 'Title of MP3' label and its text input element $html .= '&lt;label id="mp3-title" for="mp3-title"&gt;'; $html .= 'Title Of MP3'; $html .= '&lt;/label&gt;'; $html .= '&lt;input type="text" id="mp3-title" name="mp3-title" value="' . get_post_meta( $post-&gt;ID, 'mp3-title', true ) . '" placeholder="Your Song By Elton John" /&gt;'; // Display the 'MP3 File' label and its file input element $html .= '&lt;label id="mp3-file" for="mp3-file"&gt;'; $html .= 'MP3 File'; $html .= '&lt;/label&gt;'; $html .= '&lt;input type="file" id="mp3-file" name="mp3-file" value="" /&gt;'; echo $html; } </code></pre> <p>The above function is the function to render the markup in the backend?</p> <p>My question is related to this line →</p> <pre><code>if ( 'invalid-file-type' == get_post_meta( $post-&gt;ID, 'mp3', true ) ) { </code></pre> <p>It looks like to be validating whether the file is mp3 or not?</p> <p><strong>The Main Question →</strong> what if we want to validate whether this is Video file? Video files can be of multiple types and can come from many sources such Vimeo, Youtube, facebook etc.</p> <p>Additionally,</p> <p>I request the reader of this post to guide me to some specific meta where oembed has been used successfully.</p>
[ { "answer_id": 275122, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>The above function is the function to render the markup in the backend?</p>\n</blockquote>\n\n<p>Correct.</p>\n\n<blockquote>\n <p>It looks like to be validating whether the file is mp3 or not?</p>\n</blockquote>\n\n<p>No. It's just checking if the value of the meta has been set to literally the text 'invalid-file-type'. Whatever you got this from would be doing the validation in the save action, and if the filetype is invalid it sets the value of the meta to <code>'invalid-file-type'</code>.</p>\n" }, { "answer_id": 275123, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>Post's metadata can not and should not be used for validation. They can be easily manipulated. Post metadata simply stores <em>\"editable\"</em> strings or arrays, nothing more than that.</p>\n\n<p>The code you have copied is trying to fetch a metadata and check if its value is <code>mp3</code>. You can change a value of <code>exe</code> to <code>mp3</code>, and it will assume that the file is mp3. So, security issue here.</p>\n\n<p>To validate a file truly, you have to pass the files path or URL to a real validator.</p>\n\n<p>For example, WordPress offers this function to validate an image:</p>\n\n<pre><code>file_is_valid_image( $path );\n</code></pre>\n\n<p>Which returns true is the file in the pass is a real image. There are function to retrieve the file's <em>real</em> extension (since it can easily be manipulated, change .exe to .jpg), which you can find them by a simple search.</p>\n" } ]
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I am trying to learn meta's in Wordpress by taking an example of the already existing meta → ``` function cpmb_display_meta_box( $post ) { // Define the nonce for security purposes wp_nonce_field( plugin_basename( __FILE__ ), 'cpmb-nonce-field' ); // Start the HTML string so that all other strings can be concatenated $html = ''; // If the current post has an invalid file type associated with it, // then display an error message. if ( 'invalid-file-type' == get_post_meta( $post->ID, 'mp3', true ) ) { $html .= '<div id="invalid-file-type" class="error">'; $html .= '<p>You are trying to upload a file other than an MP3.</p>'; $html .= '</div>'; } // Display the 'Title of MP3' label and its text input element $html .= '<label id="mp3-title" for="mp3-title">'; $html .= 'Title Of MP3'; $html .= '</label>'; $html .= '<input type="text" id="mp3-title" name="mp3-title" value="' . get_post_meta( $post->ID, 'mp3-title', true ) . '" placeholder="Your Song By Elton John" />'; // Display the 'MP3 File' label and its file input element $html .= '<label id="mp3-file" for="mp3-file">'; $html .= 'MP3 File'; $html .= '</label>'; $html .= '<input type="file" id="mp3-file" name="mp3-file" value="" />'; echo $html; } ``` The above function is the function to render the markup in the backend? My question is related to this line → ``` if ( 'invalid-file-type' == get_post_meta( $post->ID, 'mp3', true ) ) { ``` It looks like to be validating whether the file is mp3 or not? **The Main Question →** what if we want to validate whether this is Video file? Video files can be of multiple types and can come from many sources such Vimeo, Youtube, facebook etc. Additionally, I request the reader of this post to guide me to some specific meta where oembed has been used successfully.
Post's metadata can not and should not be used for validation. They can be easily manipulated. Post metadata simply stores *"editable"* strings or arrays, nothing more than that. The code you have copied is trying to fetch a metadata and check if its value is `mp3`. You can change a value of `exe` to `mp3`, and it will assume that the file is mp3. So, security issue here. To validate a file truly, you have to pass the files path or URL to a real validator. For example, WordPress offers this function to validate an image: ``` file_is_valid_image( $path ); ``` Which returns true is the file in the pass is a real image. There are function to retrieve the file's *real* extension (since it can easily be manipulated, change .exe to .jpg), which you can find them by a simple search.
275,128
<p>I make a site of poetry. I would like to be able to display my text line by line (max 5) while it puts everything continuously.</p> <blockquote> <p>Search result:<br> Line 1<br> Line 2<br> Line 3<br> Line 4<br> Line 5</p> </blockquote> <p>On my excerpt I get this:<br> Line 1 Line 2 Line 3 Line 4 Line 5</p> <p>Can you give me a track to follow?</p> <p>Sorry, i'm french and my english is helped by google translate ;)</p> <p>EDIT</p> <p>Poetry original :<br></p> <blockquote> <p>Jour et nuit<br> Du Nord au Sud<br> D’Est en Ouest<br> En France, en Europe<br> Inlassablement,<br> Ils transportent des marchandises.<br> <br></p> </blockquote> <p>Excerpt :<br></p> <blockquote> <p>Jour et nuit Du Nord au Sud D’Est en Ouest En France, en Europe Inlassablement, Ils transportent des marchandises. <br> <br></p> </blockquote> <p>I would like :<br></p> <blockquote> <p>Jour et nuit<br> Du Nord au Sud<br> D’Est en Ouest<br> En France, en Europe<br> Inlassablement, [...]</p> </blockquote>
[ { "answer_id": 275147, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>An alternative way to look at the issue is that the excerpt is right and the way your post is being displayed is wrong.</p>\n\n<p>You should put each line of the poem as a paragraph, as if you are writing normal text, this should make the excerpt be in a multi line format. Now you should apply CSS changes to your theme that will eliminate the padding and margins between the paragraphs. The biggest challenge doing this way is to be able to identify to which posts to apply such styling.</p>\n\n<p>An easier to implement approach might be to add a css style to the editor itself, which will let you mark that a \"poem style\" should be applied to specific paragraph. </p>\n\n<p>this <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-styles-to-wordpress-visual-editor/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-styles-to-wordpress-visual-editor/</a> seems to be a relatively easy to follow guide, and this <a href=\"https://wordpress.stackexchange.com/questions/167685/add-css-class-to-link-in-tinymce-editor\">Add CSS Class to Link in TinyMCE editor</a> is more to the point.</p>\n\n<p>The challenge in the second approach is to get all the different CSS parts into their proper place, and obviously there might be more manual work in selecting the format for each paragraph.\nAnother issue that you might encounter is the styling of the excerpt itself, if it is important to you, as the excerpt generation code removes the formatting.</p>\n\n<p>If you decide to go this way, truncating an excerpt by max 5 lines becomes a relatively easy task which probably deserves a question of its own ;)</p>\n" }, { "answer_id": 275153, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>If you type your poets like this in the editor and separate them by new lines:</p>\n\n<blockquote>\n <p>This is a phrase</p>\n \n <p>This is another phrase</p>\n</blockquote>\n\n<p>Then you can divide them by new line, and then return them to the front-end. You can do this by using the <code>get_the_excerpt</code> filter. This goes in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>apply_filters( 'get_the_excerpt', 'divide_by_newline' );\nfunction divide_by_newline() {\n // Get the content of the poet\n $content = get_the_content();\n // Let's trim the excerpt by default value of 55 words\n $content = wp_trim_words( $content , 55, '...' );\n // Check if it's empty\n if( $content ) {\n // Divide the poets by new line \n $content_array = explode( \"\\n\", $content );\n // Store 5 of them into a string\n foreach( $content_array as $key=&gt;$phrase ) {\n if( $key &lt; 6 ) {\n $excerpt .= '&lt;span class=\"poet-excerpt\"&gt;'.$phrase.'&lt;/span&gt;';\n }\n }\n } else {\n $excerpt = '';\n }\n // Return the data\n return $excerpt;\n}\n</code></pre>\n\n<p>Now, your excerpt's structure will be like this:</p>\n\n<pre><code>&lt;span class=\"poet-excerpt\"&gt;This is a phrase&lt;/span&gt;\n&lt;span class=\"poet-excerpt\"&gt;This is another phrase&lt;/span&gt;\n</code></pre>\n\n<p>We're not done yet. You have to change the default view of your spans. By default, a span is an inline element, it means they will not make a new line. By using this piece of CSS, we make them behave like blocks:</p>\n\n<pre><code>.poet-excerpt{\n display:block;\n}\n</code></pre>\n\n<p>You can easily add this by heading to <code>Appearance &gt; Customizer &gt; Custom CSS</code> without modifying your <code>style.css</code>.</p>\n\n<p>But I have to mention, this works well only if you have a poet. This does not work for other excerpts.</p>\n\n<p>All done. Code is also poetry!</p>\n" } ]
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124824/" ]
I make a site of poetry. I would like to be able to display my text line by line (max 5) while it puts everything continuously. > > Search result: > Line 1 > Line 2 > Line 3 > Line 4 > Line 5 > > > On my excerpt I get this: Line 1 Line 2 Line 3 Line 4 Line 5 Can you give me a track to follow? Sorry, i'm french and my english is helped by google translate ;) EDIT Poetry original : > > Jour et nuit > Du Nord au Sud > D’Est en Ouest > En France, en > Europe > Inlassablement, > Ils transportent des marchandises. > > > > > > Excerpt : > > Jour et nuit Du Nord au Sud D’Est en Ouest En France, en Europe > Inlassablement, Ils transportent des marchandises. > > > > > I would like : > > Jour et nuit > Du Nord au Sud > D’Est en Ouest > En France, en > Europe > Inlassablement, [...] > > >
If you type your poets like this in the editor and separate them by new lines: > > This is a phrase > > > This is another phrase > > > Then you can divide them by new line, and then return them to the front-end. You can do this by using the `get_the_excerpt` filter. This goes in your theme's `functions.php` file: ``` apply_filters( 'get_the_excerpt', 'divide_by_newline' ); function divide_by_newline() { // Get the content of the poet $content = get_the_content(); // Let's trim the excerpt by default value of 55 words $content = wp_trim_words( $content , 55, '...' ); // Check if it's empty if( $content ) { // Divide the poets by new line $content_array = explode( "\n", $content ); // Store 5 of them into a string foreach( $content_array as $key=>$phrase ) { if( $key < 6 ) { $excerpt .= '<span class="poet-excerpt">'.$phrase.'</span>'; } } } else { $excerpt = ''; } // Return the data return $excerpt; } ``` Now, your excerpt's structure will be like this: ``` <span class="poet-excerpt">This is a phrase</span> <span class="poet-excerpt">This is another phrase</span> ``` We're not done yet. You have to change the default view of your spans. By default, a span is an inline element, it means they will not make a new line. By using this piece of CSS, we make them behave like blocks: ``` .poet-excerpt{ display:block; } ``` You can easily add this by heading to `Appearance > Customizer > Custom CSS` without modifying your `style.css`. But I have to mention, this works well only if you have a poet. This does not work for other excerpts. All done. Code is also poetry!
275,152
<p>I have a shordcode for Contact Form 7 form. I want use Advanced Custom Fields for ID value. How Can I do that?</p> <p>the ACF with ID value:</p> <pre><code>the_field('form'); </code></pre> <p>shordcode:</p> <pre><code>&lt;?php echo do_shortcode( '[contact-form-7 id="29"]' ); ?&gt; </code></pre> <p>Any solution? :)</p>
[ { "answer_id": 275155, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>Simple as this:</p>\n\n<pre><code>&lt;?php echo do_shortcode( '[contact-form-7 id=\"'.get_field('form').'\"]' ); ?&gt;\n</code></pre>\n\n<p>You have to notice, you should use <code>get_field()</code> to return the value. <code>the_field()</code> will echo it.</p>\n" }, { "answer_id": 351913, "author": "S2LF", "author_id": 177879, "author_profile": "https://wordpress.stackexchange.com/users/177879", "pm_score": 2, "selected": false, "text": "<p>Another way:</p>\n\n<p>Copy your shortcode in your WordPress text field:</p>\n\n<p><code>[contact-form-7 id=\"29\"]</code></p>\n\n<p>And:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php echo do_shortcode(get_field('form')); ?&gt;\n</code></pre>\n\n<p>Very small difference, a little bit easier.</p>\n" } ]
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I have a shordcode for Contact Form 7 form. I want use Advanced Custom Fields for ID value. How Can I do that? the ACF with ID value: ``` the_field('form'); ``` shordcode: ``` <?php echo do_shortcode( '[contact-form-7 id="29"]' ); ?> ``` Any solution? :)
Simple as this: ``` <?php echo do_shortcode( '[contact-form-7 id="'.get_field('form').'"]' ); ?> ``` You have to notice, you should use `get_field()` to return the value. `the_field()` will echo it.
275,205
<p>I'm new to developing with WordPress. I read <a href="https://tommcfarlin.com/sending-data-post/" rel="nofollow noreferrer">here</a> that a good way to process data posted from forms is to insert an action on the init function like so:</p> <pre><code>add_action( 'init', 'contact_form_send_email' ); </code></pre> <p>My function seems to be processing the data correctly, but I can't figure out how to make a variable available within the same template that has the form.</p> <p>What is the way to do this? I've heard that setting global variables is not a good way to go.</p>
[ { "answer_id": 275224, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>The difference between <code>add_action()</code> and <code>add_filter()</code> is semantic not technical, except that a filter expects a returned value and an action does/will not.\nThe question is whether <code>contact_form_send_email()</code> <strong>needs</strong> to be called-at /hooked-to <code>init</code>.</p>\n\n<p>If not, you can define your filter in the template with <code>apply_filters()</code>, and then hook to it to run your function and return a value to it.</p>\n\n<p>In <em>template page</em>:</p>\n\n<pre><code>$some_variable = 'some value';\n$some_variable = apply_filters('my_filter_hook', $some_variable);\n</code></pre>\n\n<p>In <em>functions.php</em></p>\n\n<pre><code>add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 );\n\nfunction contact_form_send_email( $some_variable ) {\n //do stuff\n $some_variable = 'some new value';\n\n return $some_variable;\n\n}\n</code></pre>\n\n<hr>\n\n<p>To help determine where you need to hook, this <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">Actions Reference</a> can be useful. Scroll down and you will see some template specific hooks as well.</p>\n" }, { "answer_id": 275245, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>There's an interesting feature in the WordPress that you might find it useful in situations like this. It's the ability to add something into the cache and retrieve it later.</p>\n\n<p>Since you are hooking into the init, you can retrieve your cache afterward. This is done by using the <code>wp_cache_add()</code> function:</p>\n\n<pre><code>wp_cache_add( $key, $data, $group, $expire );\n</code></pre>\n\n<p>Add whatever data you wish, and then fetch them on your template:</p>\n\n<pre><code>wp_cache_get( $key, $group );\n</code></pre>\n\n<p>You can also delete the cache afterward if you wish. Take a look at <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow noreferrer\">this</a> codex page.</p>\n" } ]
2017/07/30
[ "https://wordpress.stackexchange.com/questions/275205", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122408/" ]
I'm new to developing with WordPress. I read [here](https://tommcfarlin.com/sending-data-post/) that a good way to process data posted from forms is to insert an action on the init function like so: ``` add_action( 'init', 'contact_form_send_email' ); ``` My function seems to be processing the data correctly, but I can't figure out how to make a variable available within the same template that has the form. What is the way to do this? I've heard that setting global variables is not a good way to go.
The difference between `add_action()` and `add_filter()` is semantic not technical, except that a filter expects a returned value and an action does/will not. The question is whether `contact_form_send_email()` **needs** to be called-at /hooked-to `init`. If not, you can define your filter in the template with `apply_filters()`, and then hook to it to run your function and return a value to it. In *template page*: ``` $some_variable = 'some value'; $some_variable = apply_filters('my_filter_hook', $some_variable); ``` In *functions.php* ``` add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 ); function contact_form_send_email( $some_variable ) { //do stuff $some_variable = 'some new value'; return $some_variable; } ``` --- To help determine where you need to hook, this [Actions Reference](https://codex.wordpress.org/Plugin_API/Action_Reference) can be useful. Scroll down and you will see some template specific hooks as well.
275,218
<p>i use wp-rest-api v2 plugin. Custom post types doesnt show taxonomy. somebody can tell me whats wrong?</p> <p>URL: /wp-json/wp/v2/galeri?_embed</p> <pre><code>{ "id": 275, "date": "2016-05-07T23:53:17", "date_gmt": "2016-05-07T20:53:17", "guid": { "rendered": "http:\/\/demo.markamiz.com\/?post_type=galeri&amp;#038;p=275" }, "modified": "2017-07-21T15:07:24", "modified_gmt": "2017-07-21T12:07:24", "slug": "samsung-galaxy-s7-edge", "status": "publish", "type": "galeri", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/", "title": { "rendered": "Samsung Galaxy S7 Edge" }, "content": { "rendered": "&lt;p&gt;Toplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;1.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-276\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-1445005423.jpg\" alt=\"150604_samsung-galaxy-s7-1445005423\" width=\"580\" height=\"356\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;2.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-277\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-edge-concept-renders.jpg\" alt=\"150604_samsung-galaxy-s7-edge-concept-renders\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;3.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-278\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-1.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-1\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;4.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-279\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-2\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;5.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-280\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456\" width=\"580\" height=\"385\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;6.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-281\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-4.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-4\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;7.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-282\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-5-1.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-5\" width=\"580\" height=\"386\" \/&gt;&lt;\/p&gt;\n", "protected": false }, "excerpt": { "rendered": "&lt;p&gt;Y\u0131l\u0131n en dikkat \u00e7ekici modellerinden bir tanesi olan Samsung Galaxy S7 edge, inceleme merkezimizin yeni konu\u011fu oluyor.&lt;br \/&gt;\nSamsung, ge\u00e7ti\u011fimiz y\u0131l sat\u0131\u015fa sundu\u011fu Galaxy S6 ve Galaxy S6 edge modelleriyle tasar\u0131m dilinde ciddi bir de\u011fi\u015fikli\u011fe gitmi\u015f, plastik tasar\u0131m\u0131 tarihin tozlu sayfalar\u0131nda b\u0131rakarak cam ve metal malzemelerle haz\u0131rlanan premium tasar\u0131mlar\u0131 bizlere sunmu\u015ftu. \u00d6zellikle S6 edge ve daha sonra sat\u0131\u015fa sunulan S6 edge+, y\u0131l\u0131n en \u015f\u0131k modelleri aras\u0131nda g\u00f6sterilmi\u015fti.&lt;\/p&gt;\n", "protected": false }, "author": 4, "featured_media": 7825, "menu_order": 0, "comment_status": "open", "ping_status": "open", "template": "", "meta": [], "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/galeri" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=275" }], "version-history": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275\/revisions" }], "wp:featuredmedia": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "wp:attachment": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media?parent=275" }], "curies": [{ "name": "wp", "href": "https:\/\/api.w.org\/{rel}", "templated": true }] }, "_embedded": { "author": [{ "id": 4, "name": "Erdin\u00e7", "url": "http:\/\/www.teknoever.com", "description": "Uzun y\u0131llar bir\u00e7ok blog ve haber portallar\u0131nda edit\u00f6r olarak \u00e7al\u0131\u015fmas\u0131n\u0131n yan\u0131nda, asp ve php yaz\u0131l\u0131mlar\u0131na olduk\u00e7a hakim ve bir\u00e7ok projede b\u00fcy\u00fck ba\u015far\u0131lara imza atm\u0131\u015ft\u0131r. Edit\u00f6rl\u00fck kariyerinde \u015fimdi Tekno Ever ile devam etmektedir.Referanslar i\u00e7in l\u00fctfen markamiz.com'u ziyaret ediniz.", "link": "http:\/\/www.teknoever.com\/yazar\/erdinc\/", "slug": "erdinc", "avatar_urls": { "24": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=24&amp;d=mm&amp;r=g", "48": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=48&amp;d=mm&amp;r=g", "96": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=96&amp;d=mm&amp;r=g" }, "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users" }] } }], "wp:featuredmedia": [{ "id": 7825, "date": "2016-09-06T17:31:52", "slug": "150605_samsung-galaxy-s7-edge-concept-renders-2", "type": "attachment", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/150605_samsung-galaxy-s7-edge-concept-renders-2\/", "title": { "rendered": "150605_samsung-galaxy-s7-edge-concept-renders-2" }, "author": 4, "acf": [], "caption": { "rendered": "" }, "alt_text": "", "media_type": "image", "mime_type": "image\/jpeg", "media_details": { "width": 580, "height": 386, "file": "2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "sizes": { "thumbnail": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg", "width": 150, "height": 150, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg" }, "medium": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg", "width": 300, "height": 200, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg" }, "full": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "width": 580, "height": 386, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg" } }, "image_meta": { "aperture": "0", "credit": "", "camera": "", "caption": "", "created_timestamp": "0", "copyright": "", "focal_length": "0", "iso": "0", "shutter_speed": "0", "title": "", "orientation": "0", "keywords": [] } }, "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/attachment" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=7825" }] } }] } } </code></pre>
[ { "answer_id": 275224, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>The difference between <code>add_action()</code> and <code>add_filter()</code> is semantic not technical, except that a filter expects a returned value and an action does/will not.\nThe question is whether <code>contact_form_send_email()</code> <strong>needs</strong> to be called-at /hooked-to <code>init</code>.</p>\n\n<p>If not, you can define your filter in the template with <code>apply_filters()</code>, and then hook to it to run your function and return a value to it.</p>\n\n<p>In <em>template page</em>:</p>\n\n<pre><code>$some_variable = 'some value';\n$some_variable = apply_filters('my_filter_hook', $some_variable);\n</code></pre>\n\n<p>In <em>functions.php</em></p>\n\n<pre><code>add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 );\n\nfunction contact_form_send_email( $some_variable ) {\n //do stuff\n $some_variable = 'some new value';\n\n return $some_variable;\n\n}\n</code></pre>\n\n<hr>\n\n<p>To help determine where you need to hook, this <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">Actions Reference</a> can be useful. Scroll down and you will see some template specific hooks as well.</p>\n" }, { "answer_id": 275245, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>There's an interesting feature in the WordPress that you might find it useful in situations like this. It's the ability to add something into the cache and retrieve it later.</p>\n\n<p>Since you are hooking into the init, you can retrieve your cache afterward. This is done by using the <code>wp_cache_add()</code> function:</p>\n\n<pre><code>wp_cache_add( $key, $data, $group, $expire );\n</code></pre>\n\n<p>Add whatever data you wish, and then fetch them on your template:</p>\n\n<pre><code>wp_cache_get( $key, $group );\n</code></pre>\n\n<p>You can also delete the cache afterward if you wish. Take a look at <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow noreferrer\">this</a> codex page.</p>\n" } ]
2017/07/30
[ "https://wordpress.stackexchange.com/questions/275218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93283/" ]
i use wp-rest-api v2 plugin. Custom post types doesnt show taxonomy. somebody can tell me whats wrong? URL: /wp-json/wp/v2/galeri?\_embed ``` { "id": 275, "date": "2016-05-07T23:53:17", "date_gmt": "2016-05-07T20:53:17", "guid": { "rendered": "http:\/\/demo.markamiz.com\/?post_type=galeri&#038;p=275" }, "modified": "2017-07-21T15:07:24", "modified_gmt": "2017-07-21T12:07:24", "slug": "samsung-galaxy-s7-edge", "status": "publish", "type": "galeri", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/", "title": { "rendered": "Samsung Galaxy S7 Edge" }, "content": { "rendered": "<p>Toplam <b>7<\/b> sayfadan <b>1.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-276\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-1445005423.jpg\" alt=\"150604_samsung-galaxy-s7-1445005423\" width=\"580\" height=\"356\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>2.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-277\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-edge-concept-renders.jpg\" alt=\"150604_samsung-galaxy-s7-edge-concept-renders\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>3.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-278\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-1.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-1\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>4.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-279\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-2\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>5.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-280\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456\" width=\"580\" height=\"385\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>6.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-281\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-4.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-4\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>7.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-282\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-5-1.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-5\" width=\"580\" height=\"386\" \/><\/p>\n", "protected": false }, "excerpt": { "rendered": "<p>Y\u0131l\u0131n en dikkat \u00e7ekici modellerinden bir tanesi olan Samsung Galaxy S7 edge, inceleme merkezimizin yeni konu\u011fu oluyor.<br \/>\nSamsung, ge\u00e7ti\u011fimiz y\u0131l sat\u0131\u015fa sundu\u011fu Galaxy S6 ve Galaxy S6 edge modelleriyle tasar\u0131m dilinde ciddi bir de\u011fi\u015fikli\u011fe gitmi\u015f, plastik tasar\u0131m\u0131 tarihin tozlu sayfalar\u0131nda b\u0131rakarak cam ve metal malzemelerle haz\u0131rlanan premium tasar\u0131mlar\u0131 bizlere sunmu\u015ftu. \u00d6zellikle S6 edge ve daha sonra sat\u0131\u015fa sunulan S6 edge+, y\u0131l\u0131n en \u015f\u0131k modelleri aras\u0131nda g\u00f6sterilmi\u015fti.<\/p>\n", "protected": false }, "author": 4, "featured_media": 7825, "menu_order": 0, "comment_status": "open", "ping_status": "open", "template": "", "meta": [], "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/galeri" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=275" }], "version-history": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275\/revisions" }], "wp:featuredmedia": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "wp:attachment": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media?parent=275" }], "curies": [{ "name": "wp", "href": "https:\/\/api.w.org\/{rel}", "templated": true }] }, "_embedded": { "author": [{ "id": 4, "name": "Erdin\u00e7", "url": "http:\/\/www.teknoever.com", "description": "Uzun y\u0131llar bir\u00e7ok blog ve haber portallar\u0131nda edit\u00f6r olarak \u00e7al\u0131\u015fmas\u0131n\u0131n yan\u0131nda, asp ve php yaz\u0131l\u0131mlar\u0131na olduk\u00e7a hakim ve bir\u00e7ok projede b\u00fcy\u00fck ba\u015far\u0131lara imza atm\u0131\u015ft\u0131r. Edit\u00f6rl\u00fck kariyerinde \u015fimdi Tekno Ever ile devam etmektedir.Referanslar i\u00e7in l\u00fctfen markamiz.com'u ziyaret ediniz.", "link": "http:\/\/www.teknoever.com\/yazar\/erdinc\/", "slug": "erdinc", "avatar_urls": { "24": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=24&d=mm&r=g", "48": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=48&d=mm&r=g", "96": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=96&d=mm&r=g" }, "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users" }] } }], "wp:featuredmedia": [{ "id": 7825, "date": "2016-09-06T17:31:52", "slug": "150605_samsung-galaxy-s7-edge-concept-renders-2", "type": "attachment", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/150605_samsung-galaxy-s7-edge-concept-renders-2\/", "title": { "rendered": "150605_samsung-galaxy-s7-edge-concept-renders-2" }, "author": 4, "acf": [], "caption": { "rendered": "" }, "alt_text": "", "media_type": "image", "mime_type": "image\/jpeg", "media_details": { "width": 580, "height": 386, "file": "2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "sizes": { "thumbnail": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg", "width": 150, "height": 150, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg" }, "medium": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg", "width": 300, "height": 200, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg" }, "full": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "width": 580, "height": 386, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg" } }, "image_meta": { "aperture": "0", "credit": "", "camera": "", "caption": "", "created_timestamp": "0", "copyright": "", "focal_length": "0", "iso": "0", "shutter_speed": "0", "title": "", "orientation": "0", "keywords": [] } }, "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/attachment" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=7825" }] } }] } } ```
The difference between `add_action()` and `add_filter()` is semantic not technical, except that a filter expects a returned value and an action does/will not. The question is whether `contact_form_send_email()` **needs** to be called-at /hooked-to `init`. If not, you can define your filter in the template with `apply_filters()`, and then hook to it to run your function and return a value to it. In *template page*: ``` $some_variable = 'some value'; $some_variable = apply_filters('my_filter_hook', $some_variable); ``` In *functions.php* ``` add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 ); function contact_form_send_email( $some_variable ) { //do stuff $some_variable = 'some new value'; return $some_variable; } ``` --- To help determine where you need to hook, this [Actions Reference](https://codex.wordpress.org/Plugin_API/Action_Reference) can be useful. Scroll down and you will see some template specific hooks as well.
275,263
<p>I'm making an ajax request from my primary domain to a subdomain. I've solved my cross origin issues so I'm not getting an error. The call is returning <code>data:0</code>. I've checked my response config and the ajax url is correct as well as "action". My <code>functions.php</code> looks like this:</p> <pre><code>add_action("wp_ajax_sendhire", "sendhire"); add_action("wp_ajax_nopriv_sendhire", "sendhire"); function sendhire() { $cars = array("Volvo", "BMW", "Toyota"); return json_encode($cars); die(); } </code></pre> <p>The data, obviously, is just for testing.</p>
[ { "answer_id": 275264, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>If you want to use Admin-Ajax to output the content, you should use <code>echo</code> instead. There is nothing to be viewed when you use <code>return</code>, so you'll get a <code>0</code>.</p>\n\n<p>This quotation from the codex explains further about the <code>0</code> response:</p>\n\n<blockquote>\n <p>If the Ajax request fails in <code>wp-admin/admin-ajax.php</code>, the response\n will be -1 or 0, depending on the reason for the failure.\n Additionally, if the request succeeds, but the Ajax action does not\n match a WordPress hook defined with <code>add_action('wp_ajax_(action)',\n ...)</code> or <code>add_action('wp_ajax_nopriv_(action)', ...)</code>, then\n <code>admin-ajax.php</code> will respond 0.</p>\n</blockquote>\n\n<p>Now, if you are going to output a JSON response, you should take a look into the REST API. Its default response type is JSON.</p>\n\n<p>To do so, register a path for the endpoint, and create a callback function:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'dcp3450', '/test_endpoint/', array(\n 'methods' =&gt; 'GET', \n 'callback' =&gt; 'sendhire' \n ) );\n});\n\nfunction sendhire() {\n\n $cars = array(\"Volvo\", \"BMW\", \"Toyota\");\n return $cars;\n\n}\n</code></pre>\n\n<p>Now by accessing <code>http://example.com/wp-json/dcp3450/test_endpoint/</code> you will get your JSON response, and you can get rid of this annoying 0 that is following humanity to its end.</p>\n" }, { "answer_id": 390396, "author": "Shakeel Ahmad", "author_id": 177295, "author_profile": "https://wordpress.stackexchange.com/users/177295", "pm_score": -1, "selected": false, "text": "<p>WordPress have a very useful API (REST API) for this work, you can use it, instead of sending ajax request.\nHere is the documentation have a look please <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/</a></p>\n" } ]
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8278/" ]
I'm making an ajax request from my primary domain to a subdomain. I've solved my cross origin issues so I'm not getting an error. The call is returning `data:0`. I've checked my response config and the ajax url is correct as well as "action". My `functions.php` looks like this: ``` add_action("wp_ajax_sendhire", "sendhire"); add_action("wp_ajax_nopriv_sendhire", "sendhire"); function sendhire() { $cars = array("Volvo", "BMW", "Toyota"); return json_encode($cars); die(); } ``` The data, obviously, is just for testing.
If you want to use Admin-Ajax to output the content, you should use `echo` instead. There is nothing to be viewed when you use `return`, so you'll get a `0`. This quotation from the codex explains further about the `0` response: > > If the Ajax request fails in `wp-admin/admin-ajax.php`, the response > will be -1 or 0, depending on the reason for the failure. > Additionally, if the request succeeds, but the Ajax action does not > match a WordPress hook defined with `add_action('wp_ajax_(action)', > ...)` or `add_action('wp_ajax_nopriv_(action)', ...)`, then > `admin-ajax.php` will respond 0. > > > Now, if you are going to output a JSON response, you should take a look into the REST API. Its default response type is JSON. To do so, register a path for the endpoint, and create a callback function: ``` add_action( 'rest_api_init', function () { register_rest_route( 'dcp3450', '/test_endpoint/', array( 'methods' => 'GET', 'callback' => 'sendhire' ) ); }); function sendhire() { $cars = array("Volvo", "BMW", "Toyota"); return $cars; } ``` Now by accessing `http://example.com/wp-json/dcp3450/test_endpoint/` you will get your JSON response, and you can get rid of this annoying 0 that is following humanity to its end.
275,301
<p>I followed the instructions given in this <a href="https://getflywheel.com/layout/how-to-create-custom-meta-boxes-with-cmb2/" rel="nofollow noreferrer">blog</a> to set the CMB2 plugin, but it is not working in my case.</p> <p>theme-meta-function.php →</p> <pre><code> &lt;?php /** * Include and set up custom metaboxes and fields. (Make sure you copy this file outside the CMB2 directory) * * Be sure to replace all instances of 'yourprefix_' with your project's prefix. * http://nacin.com/2010/05/11/in-wordpress-prefix-everything/ * * @category YourThemeOrPlugin * @package Demo_CMB2 * @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later) * @link https://github.com/WebDevStudios/CMB2 */ /** * Get the bootstrap! If using the plugin from wordpress.org, REMOVE THIS! */ add_action( 'cmb2_admin_init', 'register_testimonial_metabox' ); /** * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook. */ function register_testimonial_metabox() { // Start with an underscore to hide fields from custom fields list $prefix = '_yourprefix_'; //note, you can use anything you'd like here /** * Start field groups here */ // This first field group tells WordPress where to put the fields. In the example below, it is set to show up only on Post_ID=10 $cmb_demo = new_cmb2_box( array( 'id' =&gt; $prefix . 'metabox', 'title' =&gt; __( 'Homepage Custom Fields', 'cmb2' ), 'object_types' =&gt; array( 'page', ), // Post type 'show_on' =&gt; array( 'id' =&gt; array( 10, ) ), // Specific post IDs to display this metabox ) ); $cmb_demo-&gt;add_field( array( 'name' =&gt; __( 'Testimonial Author', 'cmb2' ), 'desc' =&gt; __( 'Who is the testimonial from', 'cmb2' ), 'id' =&gt; $prefix . 'author', //Note, I renamed this to be more appropriate 'type' =&gt; 'textarea_small', ) ); $cmb_demo-&gt;add_field( array( 'name' =&gt; __( 'Testimonial', 'cmb2' ), 'desc' =&gt; __( 'add the testimonial here', 'cmb2' ), 'id' =&gt; $prefix . 'testimonial', //Note, I renamed this to be more appropriate 'type' =&gt; 'wysiwyg', 'options' =&gt; array( 'textarea_rows' =&gt; 5, ), ) ); $cmb_demo-&gt;add_field( array( 'name' =&gt; __( 'Author Image', 'cmb2' ), 'desc' =&gt; __( 'Upload an image or enter a URL.', 'cmb2' ), 'id' =&gt; $prefix . 'image', //Note, I renamed this to be more appropriate 'type' =&gt; 'file', ) ); } </code></pre> <p>then I have included like this in the functions.php →</p> <pre><code>require_once( dirname(__FILE__) . '/inc/lib/theme-meta-functions.php'); </code></pre> <p>But not a single meta is appearing the post → <a href="https://www.screencast.com/t/Bvihe62fZMV" rel="nofollow noreferrer">https://www.screencast.com/t/Bvihe62fZMV</a></p> <p>I forget to mention that the <strong>plugin is already installed</strong> in the <strong>Wordpress</strong>.</p>
[ { "answer_id": 275303, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>Change <code>$prefix = '_yourprefix_';</code> to <code>$prefix = '_wp';</code></p>\n\n<p>or add the code below directly to functions.php</p>\n\n<pre><code>add_action( 'cmb2_admin_init', 'register_testimonial_metabox' );\n\nfunction register_testimonial_metabox() {\n\n$prefix = '_wp'; \n\n$cmb_demo = new_cmb2_box( array(\n'id' =&gt; $prefix . 'metabox',\n'title' =&gt; __( 'Homepage Custom Fields', 'cmb2' ),\n'object_types' =&gt; array( 'page', ), // Post type\n'show_on' =&gt; array( 'id' =&gt; array( 10, ) ),\n) );\n\n\n$cmb_demo-&gt;add_field( array(\n'name' =&gt; __( 'Testimonial Author', 'cmb2' ),\n'desc' =&gt; __( 'Who is the testimonial from', 'cmb2' ),\n'id' =&gt; $prefix . 'author', \n) );\n\n$cmb_demo-&gt;add_field( array(\n'name' =&gt; __( 'Testimonial', 'cmb2' ),\n'desc' =&gt; __( 'add the testimonial here', 'cmb2' ),\n'id' =&gt; $prefix . 'testimonial',\n'type' =&gt; 'wysiwyg',\n'options' =&gt; array( 'textarea_rows' =&gt; 5, ),\n) );\n\n$cmb_demo-&gt;add_field( array(\n'name' =&gt; __( 'Author Image', 'cmb2' ),\n'desc' =&gt; __( 'Upload an image or enter a URL.', 'cmb2' ),\n'id' =&gt; $prefix . 'image', \n'type' =&gt; 'file',\n) );\n}\n</code></pre>\n" }, { "answer_id": 275393, "author": "The WP Intermediate", "author_id": 105791, "author_profile": "https://wordpress.stackexchange.com/users/105791", "pm_score": 1, "selected": true, "text": "<p>the solution →</p>\n\n<pre><code>'object_types' =&gt; array( 'page', ), // Post type\n 'show_on' =&gt; array( 'id' =&gt; array( 10, ) ), // Specific post IDs to display this metabox\n</code></pre>\n\n<p>the above was the reason why it was not working on a post.</p>\n\n<p>I just added post and added it here →</p>\n\n<pre><code>'object_types' =&gt; array( 'page', ), // Post type\n</code></pre>\n\n<p>and deleted this line →</p>\n\n<pre><code> 'show_on' =&gt; array( 'id' =&gt; array( 10, ) ), // Specific post \n</code></pre>\n\n<p>It all started to work, and there was no issue in the plugin or any piece of code.</p>\n" } ]
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I followed the instructions given in this [blog](https://getflywheel.com/layout/how-to-create-custom-meta-boxes-with-cmb2/) to set the CMB2 plugin, but it is not working in my case. theme-meta-function.php → ``` <?php /** * Include and set up custom metaboxes and fields. (Make sure you copy this file outside the CMB2 directory) * * Be sure to replace all instances of 'yourprefix_' with your project's prefix. * http://nacin.com/2010/05/11/in-wordpress-prefix-everything/ * * @category YourThemeOrPlugin * @package Demo_CMB2 * @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later) * @link https://github.com/WebDevStudios/CMB2 */ /** * Get the bootstrap! If using the plugin from wordpress.org, REMOVE THIS! */ add_action( 'cmb2_admin_init', 'register_testimonial_metabox' ); /** * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook. */ function register_testimonial_metabox() { // Start with an underscore to hide fields from custom fields list $prefix = '_yourprefix_'; //note, you can use anything you'd like here /** * Start field groups here */ // This first field group tells WordPress where to put the fields. In the example below, it is set to show up only on Post_ID=10 $cmb_demo = new_cmb2_box( array( 'id' => $prefix . 'metabox', 'title' => __( 'Homepage Custom Fields', 'cmb2' ), 'object_types' => array( 'page', ), // Post type 'show_on' => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox ) ); $cmb_demo->add_field( array( 'name' => __( 'Testimonial Author', 'cmb2' ), 'desc' => __( 'Who is the testimonial from', 'cmb2' ), 'id' => $prefix . 'author', //Note, I renamed this to be more appropriate 'type' => 'textarea_small', ) ); $cmb_demo->add_field( array( 'name' => __( 'Testimonial', 'cmb2' ), 'desc' => __( 'add the testimonial here', 'cmb2' ), 'id' => $prefix . 'testimonial', //Note, I renamed this to be more appropriate 'type' => 'wysiwyg', 'options' => array( 'textarea_rows' => 5, ), ) ); $cmb_demo->add_field( array( 'name' => __( 'Author Image', 'cmb2' ), 'desc' => __( 'Upload an image or enter a URL.', 'cmb2' ), 'id' => $prefix . 'image', //Note, I renamed this to be more appropriate 'type' => 'file', ) ); } ``` then I have included like this in the functions.php → ``` require_once( dirname(__FILE__) . '/inc/lib/theme-meta-functions.php'); ``` But not a single meta is appearing the post → <https://www.screencast.com/t/Bvihe62fZMV> I forget to mention that the **plugin is already installed** in the **Wordpress**.
the solution → ``` 'object_types' => array( 'page', ), // Post type 'show_on' => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox ``` the above was the reason why it was not working on a post. I just added post and added it here → ``` 'object_types' => array( 'page', ), // Post type ``` and deleted this line → ``` 'show_on' => array( 'id' => array( 10, ) ), // Specific post ``` It all started to work, and there was no issue in the plugin or any piece of code.
275,305
<p>For some of my larger WordPress sites, I would like to avoid having to copy all the media files from the live site to the development site, but instead point the development site to use the media files from the live site.</p> <p>On Drupal there is a great module for this called Stage File Proxy: <a href="https://www.drupal.org/project/stage_file_proxy" rel="nofollow noreferrer">https://www.drupal.org/project/stage_file_proxy</a></p> <p>How can I do it with Wordpress?</p>
[ { "answer_id": 275303, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>Change <code>$prefix = '_yourprefix_';</code> to <code>$prefix = '_wp';</code></p>\n\n<p>or add the code below directly to functions.php</p>\n\n<pre><code>add_action( 'cmb2_admin_init', 'register_testimonial_metabox' );\n\nfunction register_testimonial_metabox() {\n\n$prefix = '_wp'; \n\n$cmb_demo = new_cmb2_box( array(\n'id' =&gt; $prefix . 'metabox',\n'title' =&gt; __( 'Homepage Custom Fields', 'cmb2' ),\n'object_types' =&gt; array( 'page', ), // Post type\n'show_on' =&gt; array( 'id' =&gt; array( 10, ) ),\n) );\n\n\n$cmb_demo-&gt;add_field( array(\n'name' =&gt; __( 'Testimonial Author', 'cmb2' ),\n'desc' =&gt; __( 'Who is the testimonial from', 'cmb2' ),\n'id' =&gt; $prefix . 'author', \n) );\n\n$cmb_demo-&gt;add_field( array(\n'name' =&gt; __( 'Testimonial', 'cmb2' ),\n'desc' =&gt; __( 'add the testimonial here', 'cmb2' ),\n'id' =&gt; $prefix . 'testimonial',\n'type' =&gt; 'wysiwyg',\n'options' =&gt; array( 'textarea_rows' =&gt; 5, ),\n) );\n\n$cmb_demo-&gt;add_field( array(\n'name' =&gt; __( 'Author Image', 'cmb2' ),\n'desc' =&gt; __( 'Upload an image or enter a URL.', 'cmb2' ),\n'id' =&gt; $prefix . 'image', \n'type' =&gt; 'file',\n) );\n}\n</code></pre>\n" }, { "answer_id": 275393, "author": "The WP Intermediate", "author_id": 105791, "author_profile": "https://wordpress.stackexchange.com/users/105791", "pm_score": 1, "selected": true, "text": "<p>the solution →</p>\n\n<pre><code>'object_types' =&gt; array( 'page', ), // Post type\n 'show_on' =&gt; array( 'id' =&gt; array( 10, ) ), // Specific post IDs to display this metabox\n</code></pre>\n\n<p>the above was the reason why it was not working on a post.</p>\n\n<p>I just added post and added it here →</p>\n\n<pre><code>'object_types' =&gt; array( 'page', ), // Post type\n</code></pre>\n\n<p>and deleted this line →</p>\n\n<pre><code> 'show_on' =&gt; array( 'id' =&gt; array( 10, ) ), // Specific post \n</code></pre>\n\n<p>It all started to work, and there was no issue in the plugin or any piece of code.</p>\n" } ]
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275305", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85504/" ]
For some of my larger WordPress sites, I would like to avoid having to copy all the media files from the live site to the development site, but instead point the development site to use the media files from the live site. On Drupal there is a great module for this called Stage File Proxy: <https://www.drupal.org/project/stage_file_proxy> How can I do it with Wordpress?
the solution → ``` 'object_types' => array( 'page', ), // Post type 'show_on' => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox ``` the above was the reason why it was not working on a post. I just added post and added it here → ``` 'object_types' => array( 'page', ), // Post type ``` and deleted this line → ``` 'show_on' => array( 'id' => array( 10, ) ), // Specific post ``` It all started to work, and there was no issue in the plugin or any piece of code.
275,310
<p>i tried to create a simple function to receive a email when a specify user is logged, i tried with $current_user->ID and also with wp_get_current_user() but not working. This is my code:</p> <pre><code>function InvioMail() { global $current_user; $ID = $current_user-&gt;ID; $user = wp_get_current_user(); $name = $user-&gt;user_login; if ($name == 'piero') { $to = '[email protected]'; $subject = 'test su action hook wp_login'; $body = 'test su action hook pwp_login'; $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name &lt;[email protected]'); wp_mail( $to, $subject, $body, $headers ); } } add_action( 'wp_login', 'InvioMail'); </code></pre> <p>Without if condition work property but when i try with IF nothing.</p> <p>Where I'm wrong?</p>
[ { "answer_id": 275315, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>Try the code below. </p>\n\n<pre><code>function InvioMail() {\n global $current_user;\n\n if ($current_user-&gt;ID == 1){ // change id 1 to your user id \n\n $to = '[email protected]';\n $subject = 'test su action hook wp_login';\n $body = 'test su action hook pwp_login';\n $headers = array('Content-Type: text/html; charset=UTF-8','From: My \n Site Name &lt;[email protected]');\n\n wp_mail( $to, $subject, $body, $headers );\n }\n}\n\nadd_action( 'wp_login', 'InvioMail');\n</code></pre>\n" }, { "answer_id": 275320, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 3, "selected": true, "text": "<p>This should work for you, make sure that the <code>user_login</code> or <code>user_id</code> matches to the string you're using in the condition. Try to do a <code>var_dump($user_login);</code></p>\n\n<p>And about the function you're using, you don't need to grab the <code>global</code> or call <code>get_current_user();</code>, because the action you're calling already pass two parameters to your function, the first is a <code>string</code> with the <code>$user_login</code>, and the second is a <code>WP_User object</code> the current logged in user.</p>\n\n<p>To use it, just change your code to this:</p>\n\n<pre><code>function InvioMail($user_login, $user) {\n\n if ($user_login == 'piero') {\n\n $to = '[email protected]';\n $subject = 'test su action hook wp_login';\n $body = 'test su action hook pwp_login';\n $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name &lt;[email protected]');\n\n wp_mail( $to, $subject, $body, $headers );\n }\n}\n\nadd_action( 'wp_login', 'InvioMail', 10, 2);\n</code></pre>\n\n<p>To learn more about this hook, check the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow noreferrer\">Docs</a>.</p>\n" } ]
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124940/" ]
i tried to create a simple function to receive a email when a specify user is logged, i tried with $current\_user->ID and also with wp\_get\_current\_user() but not working. This is my code: ``` function InvioMail() { global $current_user; $ID = $current_user->ID; $user = wp_get_current_user(); $name = $user->user_login; if ($name == 'piero') { $to = '[email protected]'; $subject = 'test su action hook wp_login'; $body = 'test su action hook pwp_login'; $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name <[email protected]'); wp_mail( $to, $subject, $body, $headers ); } } add_action( 'wp_login', 'InvioMail'); ``` Without if condition work property but when i try with IF nothing. Where I'm wrong?
This should work for you, make sure that the `user_login` or `user_id` matches to the string you're using in the condition. Try to do a `var_dump($user_login);` And about the function you're using, you don't need to grab the `global` or call `get_current_user();`, because the action you're calling already pass two parameters to your function, the first is a `string` with the `$user_login`, and the second is a `WP_User object` the current logged in user. To use it, just change your code to this: ``` function InvioMail($user_login, $user) { if ($user_login == 'piero') { $to = '[email protected]'; $subject = 'test su action hook wp_login'; $body = 'test su action hook pwp_login'; $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name <[email protected]'); wp_mail( $to, $subject, $body, $headers ); } } add_action( 'wp_login', 'InvioMail', 10, 2); ``` To learn more about this hook, check the [Docs](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login).
275,367
<p>I am trying to create a form for customers to fill out after they have purchased a subscription and/or when they return to the site and log in. My site has multiple subscription products and I need the form to be conditional based on which product they chose. To see whether they have an active subscription I am using this code:</p> <pre><code>$customer_orders = get_posts( array( 'numberposts' =&gt; -1, 'meta_key' =&gt; '_customer_user', 'meta_value' =&gt; get_current_user_id(), 'post_type' =&gt; 'shop_subscription', 'post_status' =&gt; array_keys( wc_get_order_statuses() ), ) ); </code></pre> <p>This only returns the subscription id and status. I need to know which product was purchased with the subscription. Any help is much appreciated. Thanks!</p>
[ { "answer_id": 313071, "author": "Aliiiiiiii", "author_id": 132815, "author_profile": "https://wordpress.stackexchange.com/users/132815", "pm_score": 2, "selected": false, "text": "<p>Using the Id of a subscription you can get the subscription object :</p>\n\n<pre><code>$subscription_obj = wcs_get_subscription($sub_id);\n</code></pre>\n\n<p>wcs_get_subscription is a wrapper for the wc_get_order() method</p>\n\n<p>Then get items of your subscription :</p>\n\n<pre><code>$items = $subscription_obj -&gt;get_items();\n</code></pre>\n" }, { "answer_id": 358073, "author": "muhammad salman", "author_id": 182322, "author_profile": "https://wordpress.stackexchange.com/users/182322", "pm_score": 0, "selected": false, "text": "<pre><code> $subscriptions = wcs_get_subscriptions(['customer_id' =&gt; $user_id,'subscriptions_per_page' =&gt; -1]);\nforeach($subscriptions as $subscription){\n $subscription_id = $subscription-&gt;get_ID();\n $subscription_data = $subscription-&gt;get_data();\n}\n</code></pre>\n" } ]
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124972/" ]
I am trying to create a form for customers to fill out after they have purchased a subscription and/or when they return to the site and log in. My site has multiple subscription products and I need the form to be conditional based on which product they chose. To see whether they have an active subscription I am using this code: ``` $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_subscription', 'post_status' => array_keys( wc_get_order_statuses() ), ) ); ``` This only returns the subscription id and status. I need to know which product was purchased with the subscription. Any help is much appreciated. Thanks!
Using the Id of a subscription you can get the subscription object : ``` $subscription_obj = wcs_get_subscription($sub_id); ``` wcs\_get\_subscription is a wrapper for the wc\_get\_order() method Then get items of your subscription : ``` $items = $subscription_obj ->get_items(); ```
275,370
<p>I'm trying to develop a theme. but "Display Site Title and Tagline" checkbox not working nothing change when i check or uncheck the site tile and tagline still exist. also the color option not giving any effect? please help my code for the header text is:</p> <pre><code>&lt;header class="image-bg-fluid-height" id="startchange" style="background-image: url('&lt;?php echo( get_header_image() ); ?&gt;')" &gt; &lt;h1 class="h1-hdr"&gt;&lt;?php bloginfo('name');?&gt; &lt;/h1&gt; &lt;br/&gt; &lt;br/&gt; &lt;P id="header-pa"&gt;&lt;?php bloginfo('description');?&gt; &lt;/P&gt; &lt;a class="btn btn-primary btn-lg outline " role="button" href="#" id="btn-header"&gt;WATCH A VIDEO&lt;/a&gt; &lt;br/&gt; &lt;br/&gt; &lt;/header&gt; </code></pre>
[ { "answer_id": 281513, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 3, "selected": true, "text": "<p>this peace of code will help you </p>\n\n<pre><code> &lt;?php\n if (display_header_text()==true){\n echo '&lt;h1&gt;'.get_bloginfo( 'name' ) .'&lt;/h1&gt;';\n echo '&lt;h2&gt;'.get_bloginfo('description').'&lt;/h2&gt;'; \n } else{\n //do something\n }\n ?&gt;\n</code></pre>\n" }, { "answer_id": 316835, "author": "Cervantes01", "author_id": 152431, "author_profile": "https://wordpress.stackexchange.com/users/152431", "pm_score": 0, "selected": false, "text": "<p>The answer above didn't work for me. After examining the twenty seventeen theme I came up with this solution that worked for me. Add this to your wordpress theme page as appropriate.</p>\n\n<pre><code>&lt;?php\n $site_description = get_bloginfo( 'description', 'display' );\n\n if ( $site_description || is_customize_preview() ) :\n ?&gt;\n &lt;h2 class=\"site-description\"&gt;&lt;?php echo $site_description; ?&gt;&lt;/h2&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n\n<p>The CSS Class \"site-description\" can be defined by adding the following to your functions.php. Most sites have this set up already so if you are modifying a theme made by someone else it's worth looking for this to check the H2 Css Class name.</p>\n\n<pre><code>add_theme_support('custom-logo');\n\nfunction yourPrefix_custom_logo_setup()\n{\n $defaults = array(\n 'height' =&gt; 207,\n 'width' =&gt; 276,\n 'flex-height' =&gt; false,\n 'flex-width' =&gt; false,\n 'header-text' =&gt; array('site-title', 'yourPrefix-site-description'),\n );\n add_theme_support('custom-logo', $defaults);\n}\nadd_action('after_setup_theme', 'yourPrefix_custom_logo_setup');\n</code></pre>\n\n<p>You should change yourPrefix to whatever the prefix is for the theme that you are working on in order to prevent conflicts etc.</p>\n" }, { "answer_id": 320759, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>Above answers didn't work for me - this did. This displays the site description if the box is checked and there's text in the description field.</p>\n<pre><code>if ( (get_theme_mod('header_text') != 0) &amp;&amp; (get_bloginfo('description') != '') ) {\n echo '&lt;div class=&quot;site-description&quot;&gt;' . get_bloginfo('description') . '&lt;/div&gt;';\n}\n</code></pre>\n<p>This is also useful if you're trying to customize the display based on the Customizer's settings:</p>\n<pre><code>var_dump(get_theme_mods());\n</code></pre>\n" } ]
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124857/" ]
I'm trying to develop a theme. but "Display Site Title and Tagline" checkbox not working nothing change when i check or uncheck the site tile and tagline still exist. also the color option not giving any effect? please help my code for the header text is: ``` <header class="image-bg-fluid-height" id="startchange" style="background-image: url('<?php echo( get_header_image() ); ?>')" > <h1 class="h1-hdr"><?php bloginfo('name');?> </h1> <br/> <br/> <P id="header-pa"><?php bloginfo('description');?> </P> <a class="btn btn-primary btn-lg outline " role="button" href="#" id="btn-header">WATCH A VIDEO</a> <br/> <br/> </header> ```
this peace of code will help you ``` <?php if (display_header_text()==true){ echo '<h1>'.get_bloginfo( 'name' ) .'</h1>'; echo '<h2>'.get_bloginfo('description').'</h2>'; } else{ //do something } ?> ```
275,391
<p>I'm very new to word press having only installed it on the weekend, I'm fine with HTML &amp; CSS but PHP &amp; Wordpress is alien to me.</p> <p>I'm trying to display a post from a specific category that changes every day, i've searched everywhere and found the below code whihc works to a point.</p> <p>I just cant seem to get it to choose from a category number?</p> <p>Any help or explanation would be much appreciated.</p> <pre><code> &lt;?php if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) { $args = array('numberposts' =&gt; 1, 'orderby' =&gt; 'rand'); $totd = get_posts($args); $midnight = strtotime('midnight +1 day'); $timenow = time(); $timetillmidnight = $midnight - $timenow; echo $midnight; echo ",".$timenow; set_transient('totd_trans_post_id', $totd[0]-&gt;ID, $timetillmidnight); } else { $args = array('post__in' =&gt; array($totd_trans_post_id)); $totd = get_posts($args); } foreach( $totd as $post ) : setup_postdata($post); ?&gt; &lt;div&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre> <p><strong>EDIT</strong> Thanks for the suggestions but nothing seems to be working with my existing code, it still continues to pick a completey random post from all categories.</p>
[ { "answer_id": 275394, "author": "giolliano sulit", "author_id": 65984, "author_profile": "https://wordpress.stackexchange.com/users/65984", "pm_score": 1, "selected": false, "text": "<p>You can change your <code>get_posts $args</code></p>\n\n<p>Example:</p>\n\n<pre><code>$args = array(\n 'orderby' =&gt; 'rand',\n 'category_name' =&gt; 'your_category',\n 'showposts' =&gt; 1\n);\n</code></pre>\n" }, { "answer_id": 275406, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Just use WP_Query() to generate your custom query, <a href=\"https://codex.wordpress.org/Function_Reference/WP_Query#Category_Parameters\" rel=\"nofollow noreferrer\">category parameters.</a></p>\n\n<pre><code>&lt;?php\n$category_query_args = array(\n 'orderby' =&gt; 'rand',\n 'category_name' =&gt; 'your_category'\n);\n\n$category_query = new WP_Query( $category_query_args );\n?&gt;\n</code></pre>\n\n<p>Note: you could also pass the category <strong>slug</strong> to the query, via category_name, instead of cat.</p>\n\n<p>And just forward your loop.</p>\n\n<pre><code>&lt;?php\nif ( $category_query-&gt;have_posts() ) : while $category_query-&gt;have_posts() : $category_query-&gt;the_post();\n// Loop output goes here\nendwhile; endif;\n?&gt;\n</code></pre>\n\n<p>Hope This will help you.</p>\n" }, { "answer_id": 396158, "author": "Said Erraoudy", "author_id": 75060, "author_profile": "https://wordpress.stackexchange.com/users/75060", "pm_score": 0, "selected": false, "text": "<p>You can use this following code snippet in any theme file or you can also create a new page template. Before using this code, don’t forget to replace category IDs that you want to fetch post from.</p>\n<pre><code>&lt;?php\n\n// display random post from specific categories\n\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'cat' =&gt; '2, 6, 17, 38', // category IDs\n 'orderby' =&gt; 'rand',\n 'posts_per_page' =&gt; '1', // get 1 post only\n 'ignore_sticky_posts' =&gt; 1,\n);\n\n$my_query = new WP_Query( $args );\n\n// the loop\nif ( $my_query-&gt;have_posts() ) :\n\n while ( $my_query-&gt;have_posts() ) : $my_query-&gt;the_post();\n\n // display article\n get_template_part( 'content', 'featured' );\n\n endwhile;\n\nendif;\n\nwp_reset_postdata();\n</code></pre>\n<p>?&gt;</p>\n" } ]
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124991/" ]
I'm very new to word press having only installed it on the weekend, I'm fine with HTML & CSS but PHP & Wordpress is alien to me. I'm trying to display a post from a specific category that changes every day, i've searched everywhere and found the below code whihc works to a point. I just cant seem to get it to choose from a category number? Any help or explanation would be much appreciated. ``` <?php if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) { $args = array('numberposts' => 1, 'orderby' => 'rand'); $totd = get_posts($args); $midnight = strtotime('midnight +1 day'); $timenow = time(); $timetillmidnight = $midnight - $timenow; echo $midnight; echo ",".$timenow; set_transient('totd_trans_post_id', $totd[0]->ID, $timetillmidnight); } else { $args = array('post__in' => array($totd_trans_post_id)); $totd = get_posts($args); } foreach( $totd as $post ) : setup_postdata($post); ?> <div> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php the_content(); ?> </div> <?php endforeach; ?> ``` **EDIT** Thanks for the suggestions but nothing seems to be working with my existing code, it still continues to pick a completey random post from all categories.
You can change your `get_posts $args` Example: ``` $args = array( 'orderby' => 'rand', 'category_name' => 'your_category', 'showposts' => 1 ); ```
275,424
<pre><code> &lt;?php foreach($getPostCustom as $name=&gt;$value) { echo "&lt;strong&gt;".$name."&lt;/strong&gt;"." =&gt; "; foreach($value as $nameAr=&gt;$valueAr) { echo "&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;"; echo $nameAr." =&gt; "; echo var_dump($valueAr); } echo "&lt;br /&gt;&lt;br /&gt;"; } ?&gt; </code></pre> <p>Actually I created a "Custom Post Type" and for that post type I added Custom Fields and Now I want to Display all my custom field values in the particular post type posts. The above Code displays all Custom Fields. Please help me to retrieve only custom fields of the particular Posts Only. Thanks In Advance..</p>
[ { "answer_id": 275430, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>If you're in the <code>single_{$post_type_slug}</code> template . you can do this way:</p>\n\n<pre><code>// Create an array with the name of all custom field\n\n$custom_field_names = array( 'custom_field1', 'custom_field2' );\n$custom_fields;\n\n$args = array (\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; -1\n);\n\n$posts = get_posts( $args );\n\n// Get all the custom fields for this post\n\nforeach( $posts as $key =&gt; $post ) {\n foreach( $custom_fields_names as $name ) {\n $custom_fields[$key][$name] = get_field( $name, $post-&gt;ID )\n }\n} \n</code></pre>\n" }, { "answer_id": 275738, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 2, "selected": true, "text": "<pre><code> &lt;div class=\"col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column\"&gt; &lt;?php\n if (have_posts()) : \n while (have_posts()) : the_post(); ?&gt;\n &lt;h1&gt; &lt;?php the_title();?&gt; &lt;/h1&gt; &lt;?php \n $post_meta = get_post_meta(get_the_ID());\n foreach($post_meta as $key=&gt;$value)\n { \n echo \"&lt;strong&gt;\".$key.\"&lt;/strong&gt;\".\" =&gt; \";\n foreach($value as $nameAr=&gt;$valueAr)\n {\n echo \"&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;\";\n echo $nameAr.\" =&gt; \".$valueAr; \n }\n echo \"&lt;br &gt;\"; \n }\n the_content(); \n endwhile;\n endif; ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275424", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97802/" ]
``` <?php foreach($getPostCustom as $name=>$value) { echo "<strong>".$name."</strong>"." => "; foreach($value as $nameAr=>$valueAr) { echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo $nameAr." => "; echo var_dump($valueAr); } echo "<br /><br />"; } ?> ``` Actually I created a "Custom Post Type" and for that post type I added Custom Fields and Now I want to Display all my custom field values in the particular post type posts. The above Code displays all Custom Fields. Please help me to retrieve only custom fields of the particular Posts Only. Thanks In Advance..
``` <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1> <?php the_title();?> </h1> <?php $post_meta = get_post_meta(get_the_ID()); foreach($post_meta as $key=>$value) { echo "<strong>".$key."</strong>"." => "; foreach($value as $nameAr=>$valueAr) { echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo $nameAr." => ".$valueAr; } echo "<br >"; } the_content(); endwhile; endif; ?> </div> ```
275,439
<p>Thanks in advance for all your help! </p> <p>I want to display posts (tours) that are in a specific location (city) so in my location_taxonomy.php I have a taxonomy query in the form of:</p> <pre><code>$args = array( 'post_type' =&gt; 'tour', 'meta_key' =&gt; 'trav_tour_city', 'meta_value' =&gt; $term-&gt;term_id, //city id ); </code></pre> <p>When the key stored in the tour has only one value (one city), it displays the posts. When the key has more than one value (multiple cities or id separated by commas), it doesn't.</p> <p>How can I change the $args so the query would determine that the current city ($term->term_id) exists within the comma separated values stored in 'trav_tour_city'?</p> <p>I have tried something in the line of:</p> <pre><code> // trying multiple cities $args = array( array( 'post_type' =&gt; 'tour', 'meta_key' =&gt; 'trav_tour_city', 'meta_query' =&gt; array( array( 'value' =&gt; $term-&gt;term_id, 'compare' =&gt; 'IN', ), ), ), ); </code></pre> <p>but obviously I don't know what I'm doing... haha.. </p> <p>Thanks guys... </p>
[ { "answer_id": 275430, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>If you're in the <code>single_{$post_type_slug}</code> template . you can do this way:</p>\n\n<pre><code>// Create an array with the name of all custom field\n\n$custom_field_names = array( 'custom_field1', 'custom_field2' );\n$custom_fields;\n\n$args = array (\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; -1\n);\n\n$posts = get_posts( $args );\n\n// Get all the custom fields for this post\n\nforeach( $posts as $key =&gt; $post ) {\n foreach( $custom_fields_names as $name ) {\n $custom_fields[$key][$name] = get_field( $name, $post-&gt;ID )\n }\n} \n</code></pre>\n" }, { "answer_id": 275738, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 2, "selected": true, "text": "<pre><code> &lt;div class=\"col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column\"&gt; &lt;?php\n if (have_posts()) : \n while (have_posts()) : the_post(); ?&gt;\n &lt;h1&gt; &lt;?php the_title();?&gt; &lt;/h1&gt; &lt;?php \n $post_meta = get_post_meta(get_the_ID());\n foreach($post_meta as $key=&gt;$value)\n { \n echo \"&lt;strong&gt;\".$key.\"&lt;/strong&gt;\".\" =&gt; \";\n foreach($value as $nameAr=&gt;$valueAr)\n {\n echo \"&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;\";\n echo $nameAr.\" =&gt; \".$valueAr; \n }\n echo \"&lt;br &gt;\"; \n }\n the_content(); \n endwhile;\n endif; ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125022/" ]
Thanks in advance for all your help! I want to display posts (tours) that are in a specific location (city) so in my location\_taxonomy.php I have a taxonomy query in the form of: ``` $args = array( 'post_type' => 'tour', 'meta_key' => 'trav_tour_city', 'meta_value' => $term->term_id, //city id ); ``` When the key stored in the tour has only one value (one city), it displays the posts. When the key has more than one value (multiple cities or id separated by commas), it doesn't. How can I change the $args so the query would determine that the current city ($term->term\_id) exists within the comma separated values stored in 'trav\_tour\_city'? I have tried something in the line of: ``` // trying multiple cities $args = array( array( 'post_type' => 'tour', 'meta_key' => 'trav_tour_city', 'meta_query' => array( array( 'value' => $term->term_id, 'compare' => 'IN', ), ), ), ); ``` but obviously I don't know what I'm doing... haha.. Thanks guys...
``` <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1> <?php the_title();?> </h1> <?php $post_meta = get_post_meta(get_the_ID()); foreach($post_meta as $key=>$value) { echo "<strong>".$key."</strong>"." => "; foreach($value as $nameAr=>$valueAr) { echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo $nameAr." => ".$valueAr; } echo "<br >"; } the_content(); endwhile; endif; ?> </div> ```
275,445
<p>I am using <a href="https://wordpress.org/plugins/wck-custom-fields-and-custom-post-types-creator/" rel="nofollow noreferrer">this plugin</a> to create custom fields and custom post-types. I am able to create repeater custom fields in the following format.</p> <pre><code>1 Dummy Name1 Location1 2 Dummy Name2 Location2 ..... and so on </code></pre> <p>This field values are repeated and can be created n number of time. What I have trouble doing is this format</p> <pre><code>Session 2015-16 1 Dummy Name1 Location1 2 Dummy Name2 Location2 Session 2016-17 11 Dummy Name11 Location11 12 Dummy Name12 Location12 Session 2018-19 21 Dummy Name21 Location21 22 Dummy Name22 Location22 ..... and so on </code></pre> <p>Is it possible to create such format with the same plugin? If not how is it possible to create such layout.</p> <p>Thanks, Puneet</p>
[ { "answer_id": 275460, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 0, "selected": false, "text": "<p>I don't know about that plugin but I know you could easily do that with <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">ACF</a> repeater fields</p>\n\n<p><a href=\"https://www.advancedcustomfields.com/resources/repeater/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/repeater/</a></p>\n" }, { "answer_id": 275482, "author": "Will", "author_id": 125044, "author_profile": "https://wordpress.stackexchange.com/users/125044", "pm_score": -1, "selected": false, "text": "<p>I couldn't see how it could be done with that plugin, perhaps take a look at <a href=\"https://is.gd/nested_repeating_fields\" rel=\"nofollow noreferrer\">WP-Types</a> they offer this. There is a video explainer on this page <a href=\"https://is.gd/nested_repeating_fields\" rel=\"nofollow noreferrer\">https://is.gd/nested_repeating_fields</a></p>\n" }, { "answer_id": 275513, "author": "Anh Tran", "author_id": 2051, "author_profile": "https://wordpress.stackexchange.com/users/2051", "pm_score": 0, "selected": false, "text": "<p>You can definitely do that with <a href=\"https://metabox.io\" rel=\"nofollow noreferrer\">Meta Box</a> plugin along with its <a href=\"https://metabox.io/plugins/meta-box-group/\" rel=\"nofollow noreferrer\">Group extension</a>.</p>\n\n<p>The extension allows you reorganize your data in a better structure. Your data will be saved in an array instead of plain text field like normal WordPress fields.</p>\n\n<p>It support <strong>multi-level nested arrays</strong> (along with the data) and <strong>clone features</strong> (repeating), so you can create as many clones as you want (both for the outer groups and the inner groups).</p>\n\n<p>You can see a quick screenshot about it here (which is similar to what you asked):</p>\n\n<p><img src=\"https://mb-static.surge.sh/extensions/group.png\" alt=\"meta box group\"></p>\n\n<p>You can see more info about it on <a href=\"https://metabox.io/plugins/meta-box-group/\" rel=\"nofollow noreferrer\">its own page</a>.</p>\n\n<p>Disclaimer: I'm the author of the plugins and if you have any question, I'm happy to answer.</p>\n" } ]
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99340/" ]
I am using [this plugin](https://wordpress.org/plugins/wck-custom-fields-and-custom-post-types-creator/) to create custom fields and custom post-types. I am able to create repeater custom fields in the following format. ``` 1 Dummy Name1 Location1 2 Dummy Name2 Location2 ..... and so on ``` This field values are repeated and can be created n number of time. What I have trouble doing is this format ``` Session 2015-16 1 Dummy Name1 Location1 2 Dummy Name2 Location2 Session 2016-17 11 Dummy Name11 Location11 12 Dummy Name12 Location12 Session 2018-19 21 Dummy Name21 Location21 22 Dummy Name22 Location22 ..... and so on ``` Is it possible to create such format with the same plugin? If not how is it possible to create such layout. Thanks, Puneet
I don't know about that plugin but I know you could easily do that with [ACF](https://www.advancedcustomfields.com/) repeater fields <https://www.advancedcustomfields.com/resources/repeater/>
275,485
<p>I am trying to use ACF Pro Select field to display a specify social media icons. So I have this code in my theme:</p> <pre><code>&lt;?php if( get_field('social_medias', 'option') == 'facebook' ): ?&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"&gt; &lt;path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"&gt;&lt;/path&gt;&lt;/svg&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; </code></pre> <p>"social_medias" is the SELECT field with several options, like Facebook or Twitter. What's wrong with this code? It's doesn't seems to works :D</p>
[ { "answer_id": 275486, "author": "Nuuu", "author_id": 124591, "author_profile": "https://wordpress.stackexchange.com/users/124591", "pm_score": 1, "selected": false, "text": "<p>I would do this instead:</p>\n\n<pre><code> &lt;?php\n if( have_rows('social_medias', 'option') ):\n while ( have_rows('social_medias', 'option') ) : the_row();\n $type = get_sub_field('type');\n if ($type == \"facebook\") {\n\n } elseif ($type == \"twitter\") {\n\n }\n endwhile;\n endif;\n ?&gt;\n</code></pre>\n" }, { "answer_id": 275487, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>There could be several things wrong here. I'll run through trouble shooting.</p>\n\n<p>Remember that when you're putting in your information for the select options that \"facebook\" doesn't equal \"Facebook\".\nso this </p>\n\n<pre><code>&lt;?php if( get_field('social_medias', 'option') == 'facebook' ): ?&gt;\n</code></pre>\n\n<p>may need to be </p>\n\n<pre><code>&lt;?php if( get_field('social_medias', 'option') == 'Facebook' ): ?&gt;\n</code></pre>\n\n<p>If you're not using values and labels, make sure you have the correct option chosen in the field options page to only return values. if you have values and labels, and you're returning both then maybe this code will work:</p>\n\n<pre><code>&lt;?php if( get_field('social_medias', 'option')['value'] == 'facebook' ): ?&gt;\n</code></pre>\n\n<p>again making sure that you're aware of capital or lowercase.</p>\n" }, { "answer_id": 275488, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 3, "selected": true, "text": "<p>You can loop through your ACF options by using the code below.</p>\n\n<pre><code>&lt;?php if( have_rows('social_medias', 'option') ):\n\n while ( have_rows('social_medias', 'option') ) : the_row(); \n\n $type = get_sub_field('type'); ?&gt;\n\n\n &lt;?php if ($type == \"facebook\") { ?&gt;\n\n &lt;li&gt;\n &lt;a href=\"#\"&gt;\n &lt;svg viewbox=\"0 0 6.5 14\" xmlns=\"http://www.w3.org/2000/svg\"&gt;\n &lt;path class=\"st0\" d=\"M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z\" id=\"Layer_3\"&gt;&lt;/path&gt;&lt;/svg&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n\n &lt;?php } elseif ($type == \"twitter\") { ?&gt;\n\n &lt;li&gt;\n &lt;a href=\"#\"&gt;\n &lt;svg viewbox=\"0 0 6.5 14\" xmlns=\"http://www.w3.org/2000/svg\"&gt;\n &lt;path class=\"st0\" d=\"M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z\" id=\"Layer_3\"&gt;&lt;/path&gt;&lt;/svg&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n\n &lt;?php } elseif ($type == \"google\") { ?&gt;\n\n &lt;li&gt;\n &lt;a href=\"#\"&gt;\n &lt;svg viewbox=\"0 0 6.5 14\" xmlns=\"http://www.w3.org/2000/svg\"&gt;\n &lt;path class=\"st0\" d=\"M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z\" id=\"Layer_3\"&gt;&lt;/path&gt;&lt;/svg&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n\n\n&lt;?php } endwhile; endif; ?&gt;\n</code></pre>\n" } ]
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I am trying to use ACF Pro Select field to display a specify social media icons. So I have this code in my theme: ``` <?php if( get_field('social_medias', 'option') == 'facebook' ): ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php endif; ?> ``` "social\_medias" is the SELECT field with several options, like Facebook or Twitter. What's wrong with this code? It's doesn't seems to works :D
You can loop through your ACF options by using the code below. ``` <?php if( have_rows('social_medias', 'option') ): while ( have_rows('social_medias', 'option') ) : the_row(); $type = get_sub_field('type'); ?> <?php if ($type == "facebook") { ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php } elseif ($type == "twitter") { ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php } elseif ($type == "google") { ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php } endwhile; endif; ?> ```
275,491
<p>please help me: I need to get the parent of the current page, in other words: to get the parent of $direct_parent.Thanks!</p> <pre><code>&lt;?php global $post; $direct_parent = $post-&gt;post_parent; $parent = $direct_parent-&gt;post_parent; wp_list_pages( array( 'child_of' =&gt; $parent, 'title_li' =&gt; false, 'depth' =&gt; 1 ) ); ?&gt; </code></pre> <p>This code doesn't work(</p>
[ { "answer_id": 275492, "author": "Sabbir Hasan", "author_id": 76587, "author_profile": "https://wordpress.stackexchange.com/users/76587", "pm_score": 2, "selected": false, "text": "<p>Try using <strong>get_post_ancestors</strong>. Here is how you can apply this in your case:</p>\n\n<pre><code>&lt;?php\n global $wp_query;\n $post = $wp_query-&gt;post;\n $ancestors = get_post_ancestors($post);\n if( empty($post-&gt;post_parent) ) {\n $parent = $post-&gt;ID;\n } else {\n $parent = end($ancestors);\n } \n if(wp_list_pages(\"title_li=&amp;child_of=$parent&amp;echo=0\" )) { \n wp_list_pages(\"title_li=&amp;child_of=$parent&amp;depth=1\" ); \n } \n?&gt;\n</code></pre>\n\n<p>You'll probably need to remove the depth parameters to show you're 3rd level pages.</p>\n\n<p>Let me know if this helps!</p>\n" }, { "answer_id": 275540, "author": "Manoj Mohan", "author_id": 125085, "author_profile": "https://wordpress.stackexchange.com/users/125085", "pm_score": 0, "selected": false, "text": "<p>Replace <code>$parent</code> in <code>child_of</code> argument of <code>wp_list_pages</code> by <code>parent-&gt;ID</code>.\n<code>wp_list_pages</code> needs the post id instead of post object.</p>\n\n<pre><code>&lt;?php \n global $post;\n $direct_parent = $post-&gt;post_parent;\n $parent = $direct_parent-&gt;post_parent;\n wp_list_pages( array(\n 'child_of' =&gt; $parent,\n 'title_li' =&gt; false,\n 'depth' =&gt; 1\n ) );\n?&gt;\n</code></pre>\n" } ]
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125046/" ]
please help me: I need to get the parent of the current page, in other words: to get the parent of $direct\_parent.Thanks! ``` <?php global $post; $direct_parent = $post->post_parent; $parent = $direct_parent->post_parent; wp_list_pages( array( 'child_of' => $parent, 'title_li' => false, 'depth' => 1 ) ); ?> ``` This code doesn't work(
Try using **get\_post\_ancestors**. Here is how you can apply this in your case: ``` <?php global $wp_query; $post = $wp_query->post; $ancestors = get_post_ancestors($post); if( empty($post->post_parent) ) { $parent = $post->ID; } else { $parent = end($ancestors); } if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { wp_list_pages("title_li=&child_of=$parent&depth=1" ); } ?> ``` You'll probably need to remove the depth parameters to show you're 3rd level pages. Let me know if this helps!