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
|
---|---|---|---|---|---|---|
231,114 |
<p>I have a loop that pulls in all sites in my multisite site network and loops through them to get variables located in their ACF options. Here is an excerpt from the code I am using:</p>
<pre><code> $stageurl = array();
$args = array(
'public' => true,
'limit' => 500
);
$sites = wp_get_sites($args);
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
$stage = get_field('stage', 'option');
if (isset($stage)) {
$stageurl[] = $site['domain'];
}
restore_current_blog();
}
foreach ($stageurl as $i => $stages) {
...
}
</code></pre>
<p>Using wp_get_sites, how are sites sorted by default?</p>
<p>Ideally I would like to sort sites by their creation date before adding them to my foreach loop. Is it possible to find a network site's creation date and use it to sort my $stageurl array?</p>
|
[
{
"answer_id": 231121,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>Using <code>get_sites()</code> in WP 4.6+</h2>\n\n<p>It looks like <code>wp_get_sites()</code> will be <a href=\"https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/ms-deprecated.php#L442\" rel=\"nofollow\">deprecated</a> in WP 4.6.</p>\n\n<p>The <a href=\"https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/ms-blogs.php#L608-612\" rel=\"nofollow\">new replacement</a> is:</p>\n\n<pre><code>function get_sites( $args = array() ) {\n $query = new WP_Site_Query();\n\n return $query->query( $args );\n}\n</code></pre>\n\n<p>Very similar to <code>get_posts()</code> and <code>WP_Query</code>.</p>\n\n<p>It supports various useful parameters and filters.</p>\n\n<p>Here's what the <a href=\"https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/class-wp-site-query.php#L120\" rel=\"nofollow\">inline documentation says</a> about the <code>orderby</code> input parameter:</p>\n\n<ul>\n<li>Site status or array of statuses. </li>\n<li>Default <code>id</code></li>\n<li><p>Accepts:</p>\n\n<ul>\n<li><code>id</code></li>\n<li><code>domain</code></li>\n<li><code>path</code> </li>\n<li><code>network_id</code> </li>\n<li><code>last_updated</code> </li>\n<li><code>registered</code></li>\n<li><code>domain_length</code> </li>\n<li><code>path_length</code></li>\n<li><code>site__in</code> </li>\n<li><code>network__in</code></li>\n</ul></li>\n<li><p>Also accepts the following to disable <code>ORDER BY</code> clause: </p>\n\n<ul>\n<li><code>false</code></li>\n<li>an empty array</li>\n<li><code>none</code></li>\n</ul></li>\n</ul>\n\n<p>The default of the <code>order</code> parameter is <code>DESC</code>.</p>\n\n<h2>Example</h2>\n\n<p>Here's an example (untested) how we might try to order <em>public</em> sites by <em>registration</em> date:</p>\n\n<pre><code>$mysites = get_sites( \n [\n 'public' => 1,\n 'number' => 500,\n 'orderby' => 'registered',\n 'order' => 'DESC',\n ]\n);\n</code></pre>\n\n<p>and returning at max 500 sites.</p>\n\n<h2>Update</h2>\n\n<p>Thanks to @fostertime for noticing that the <em>boolean</em> value of the <code>public</code> parameter. It's not supported. It should be <code>1</code> not <code>true</code> in the example here above.</p>\n\n<p>I therefore filed a ticket <a href=\"https://core.trac.wordpress.org/ticket/37937\" rel=\"nofollow\">here</a> (#37937) to support <em>boolean</em> strings for the <code>public</code>, <code>archived</code>, <code>mature</code>, <code>spam</code> and <code>deleted</code> attributes in <code>WP_Site_Query</code>.</p>\n"
},
{
"answer_id": 231200,
"author": "Morgan",
"author_id": 88515,
"author_profile": "https://wordpress.stackexchange.com/users/88515",
"pm_score": 2,
"selected": false,
"text": "<p>I wasn't able to get <code>get_sites</code> working, so here is a solution using <code>wp_get_sites</code> until further documentation is released on the new version. </p>\n\n<p><code>wp_get_sites</code> returns a lot of data about the subsite, including creation and last modified dates. I turned my original $stageurl array into a multidimensional array and added registration date as a value. The default value returned was a string, so I converted it to time before calling it. Finally, I sorted it to show the newest sites first and oldest sites at the end of the list.</p>\n\n<pre><code>foreach ($sites as $site) {\n switch_to_blog($site['blog_id']);\n $stage = get_field('stage', 'option');\n $registered = strtotime($site['registered']);\n\n if (isset($stage)) {\n $stageurl[] = array('domain' => $site['domain'], 'registered' => $registered);\n }\n\n restore_current_blog();\n}\n\nusort($stageurl, function($a, $b) {\n return $b['registered'] - $a['registered'];\n});\n</code></pre>\n"
},
{
"answer_id": 237015,
"author": "fostertime",
"author_id": 90145,
"author_profile": "https://wordpress.stackexchange.com/users/90145",
"pm_score": 3,
"selected": false,
"text": "<p>@birgire get_sites() example is the correct way. I would have just added this as a comment, but don't have enough dang reputation!</p>\n\n<p>The only change, is that public accepts an integer, not a bool. See <a href=\"https://developer.wordpress.org/reference/functions/get_sites/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/get_sites/</a></p>\n\n<pre><code>$mysites = get_sites( \n [\n 'public' => 1,\n 'number' => 500,\n 'orderby' => 'id',\n 'order' => 'ASC',\n ]\n);\n</code></pre>\n"
},
{
"answer_id": 240214,
"author": "Lance Cleveland",
"author_id": 11553,
"author_profile": "https://wordpress.stackexchange.com/users/11553",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my code for running through sites in WP 4.6 and sites using WP < 4.6. If you are producing themes or plugins to be used by the general public you have no control over which version of WordPress they are using.</p>\n\n<p>The problem is not just the parameter changes between get_sites and wp_get_sites but also that WordPress 4.6 has changed the return value from an array to an object. Therefore you need to reference your elements differently.</p>\n\n<p>Here I first check that the WP 4.6 function is available and use that with the object version first. I then move on to checking that pre 4.6 wp_get_sites and try doing that iteration next.</p>\n\n<pre><code> // WordPress 4.6\n //\n if ( function_exists( 'get_sites' ) && class_exists( 'WP_Site_Query' ) ) {\n $sites = get_sites();\n foreach ( $sites as $site ) {\n switch_to_blog( $site->blog_id );\n // do something\n restore_current_blog();\n }\n return;\n }\n\n // WordPress < 4.6\n //\n if ( function_exists( 'wp_get_sites' ) ) {\n $sites = wp_get_sites();\n foreach ( $sites as $site ) {\n switch_to_blog( $site['blog_id'] );\n // do something\n restore_current_blog();\n }\n return;\n }\n</code></pre>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88515/"
] |
I have a loop that pulls in all sites in my multisite site network and loops through them to get variables located in their ACF options. Here is an excerpt from the code I am using:
```
$stageurl = array();
$args = array(
'public' => true,
'limit' => 500
);
$sites = wp_get_sites($args);
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
$stage = get_field('stage', 'option');
if (isset($stage)) {
$stageurl[] = $site['domain'];
}
restore_current_blog();
}
foreach ($stageurl as $i => $stages) {
...
}
```
Using wp\_get\_sites, how are sites sorted by default?
Ideally I would like to sort sites by their creation date before adding them to my foreach loop. Is it possible to find a network site's creation date and use it to sort my $stageurl array?
|
Using `get_sites()` in WP 4.6+
------------------------------
It looks like `wp_get_sites()` will be [deprecated](https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/ms-deprecated.php#L442) in WP 4.6.
The [new replacement](https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/ms-blogs.php#L608-612) is:
```
function get_sites( $args = array() ) {
$query = new WP_Site_Query();
return $query->query( $args );
}
```
Very similar to `get_posts()` and `WP_Query`.
It supports various useful parameters and filters.
Here's what the [inline documentation says](https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/class-wp-site-query.php#L120) about the `orderby` input parameter:
* Site status or array of statuses.
* Default `id`
* Accepts:
+ `id`
+ `domain`
+ `path`
+ `network_id`
+ `last_updated`
+ `registered`
+ `domain_length`
+ `path_length`
+ `site__in`
+ `network__in`
* Also accepts the following to disable `ORDER BY` clause:
+ `false`
+ an empty array
+ `none`
The default of the `order` parameter is `DESC`.
Example
-------
Here's an example (untested) how we might try to order *public* sites by *registration* date:
```
$mysites = get_sites(
[
'public' => 1,
'number' => 500,
'orderby' => 'registered',
'order' => 'DESC',
]
);
```
and returning at max 500 sites.
Update
------
Thanks to @fostertime for noticing that the *boolean* value of the `public` parameter. It's not supported. It should be `1` not `true` in the example here above.
I therefore filed a ticket [here](https://core.trac.wordpress.org/ticket/37937) (#37937) to support *boolean* strings for the `public`, `archived`, `mature`, `spam` and `deleted` attributes in `WP_Site_Query`.
|
231,118 |
<p>I hope this is not too specific to WooCommerce.</p>
<p>I have a nifty shortcode that displays a list of all my products with SKUs. However, it also includes products that I have published but have set the catalog visibility to "hidden." </p>
<p>I can't find an argument / parameter to exclude hidden products (or only include those marked as Catalog/Search).</p>
<p>I know it must be simple; I just haven't found it. Thanks for any help.</p>
<p>Here is the code:</p>
<pre><code><?php
$params = array('posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'menu-order', 'order' => 'asc');
$wc_query = new WP_Query($params);
?>
<table class="product-list tablesorter"><thead><tr><th>SKU</th><th>Product Name</th></tr></thead><tbody>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<tr>
<td><?php global $product; echo $product->get_sku(); ?></td>
<td><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></td>
</tr>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<tr><td>
<?php _e( 'No Products' ); ?>
</td> </tr>
<?php endif; ?>
</tbody>
</table>
</code></pre>
|
[
{
"answer_id": 231120,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Important:</strong> The following only works for WooCommerce versions less than 3.0. For a more up-to-date answer please see the other <a href=\"https://wordpress.stackexchange.com/a/262628/7355\">answer by kalle</a>.</p>\n\n<p>WooCommerce save this data as <code>metadata</code> so you'll need to run a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Meta Query</a> against the name <code>_visibility</code>. Something like:</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => '_visibility',\n 'value' => 'hidden',\n 'compare' => '!=',\n )\n)\n</code></pre>\n\n<p>This will pull all posts that <strong>do not</strong> have meta <code>_visibility</code> equal to <code>hidden</code>.</p>\n"
},
{
"answer_id": 262628,
"author": "kalle",
"author_id": 117027,
"author_profile": "https://wordpress.stackexchange.com/users/117027",
"pm_score": 5,
"selected": false,
"text": "<p>As of Woocommerce 3. Visibility is <a href=\"https://github.com/woocommerce/woocommerce/wiki/2.6.x-to-3.0.0-Developer-Migration-Notes#product-visibility-is-taxonomy-based-instead-of-meta-based\" rel=\"noreferrer\">changed to taxonomy instead of meta</a>. So you need to change the meta_query to tax_query.\nTo show only visible products,</p>\n\n<pre><code>'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'exclude-from-catalog',\n 'operator' => 'NOT IN',\n ),\n),\n</code></pre>\n\n<p>and examples for Featured Products</p>\n\n<pre><code>'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n),\n</code></pre>\n\n<p>Possible terms: 'exclude-from-search', 'exclude-from-catalog', 'featured', 'outofstock'.</p>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231118",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97616/"
] |
I hope this is not too specific to WooCommerce.
I have a nifty shortcode that displays a list of all my products with SKUs. However, it also includes products that I have published but have set the catalog visibility to "hidden."
I can't find an argument / parameter to exclude hidden products (or only include those marked as Catalog/Search).
I know it must be simple; I just haven't found it. Thanks for any help.
Here is the code:
```
<?php
$params = array('posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'menu-order', 'order' => 'asc');
$wc_query = new WP_Query($params);
?>
<table class="product-list tablesorter"><thead><tr><th>SKU</th><th>Product Name</th></tr></thead><tbody>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<tr>
<td><?php global $product; echo $product->get_sku(); ?></td>
<td><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></td>
</tr>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<tr><td>
<?php _e( 'No Products' ); ?>
</td> </tr>
<?php endif; ?>
</tbody>
</table>
```
|
**Important:** The following only works for WooCommerce versions less than 3.0. For a more up-to-date answer please see the other [answer by kalle](https://wordpress.stackexchange.com/a/262628/7355).
WooCommerce save this data as `metadata` so you'll need to run a [Meta Query](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) against the name `_visibility`. Something like:
```
'meta_query' => array(
array(
'key' => '_visibility',
'value' => 'hidden',
'compare' => '!=',
)
)
```
This will pull all posts that **do not** have meta `_visibility` equal to `hidden`.
|
231,123 |
<p>I have used <code>WP-Mail-SMTP</code> to setup the mailer on my WordPress installation.
I have tested it by sending email to my private mail.</p>
<p>I am now trying to send the form data using wp_mail() function[WP]. </p>
<p>Below is the code.</p>
<pre><code><?php
if(isset($_POST["button_pressed"])){
// Checking For Blank Fields..
if($_POST["dname"]==""){
echo "Fill All Fields..";
}
else {
$email=$_POST['email'];
$message = $_POST['dname'];
$headers = 'From:' . "\r\n"; // Sender's Email
$headers .= 'Cc:' . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
// $message = wordwrap($message, 70);
wp_mail("PRIVATE-EMAIL-ADDRESS", $subject, $message, $headers)
echo "Your mail has been sent successfully ! Thank you for your feedback";
}
?>
</code></pre>
<p>HTML form</p>
<pre><code><form>
<div class="row">
<div class="form-group">
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER DOG'S NAME" id="dname" /></div>
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" id="name" /></div>
</div>
</div>
<input type="submit" value="SUBMIT" />
<input type="hidden" name="button_pressed" value="1" />
</form>
</code></pre>
<p>I have tried many tutorials, but none helped.
Your comments and suggestions will be very helpful to me.
Thanks for your time.</p>
|
[
{
"answer_id": 231129,
"author": "Syed Fakhar Abbas",
"author_id": 90591,
"author_profile": "https://wordpress.stackexchange.com/users/90591",
"pm_score": 0,
"selected": false,
"text": "<p>I have checked your code. I think header not defined properly.Please check the code below:</p>\n\n<pre><code>$current_user = wp_get_current_user();\n$name = sanitize_text_field($_POST[\"name\"]);\n$email_address = sanitize_email($_POST[\"email_address\"]);\n$detail = esc_textarea($_POST[\"detail\"]);\n$message = \"Name : \" . $name . \"\\n\";\n$message .= \"Email Address : \" . $email_address . \"\\n\";\n$message .= \"Detail : \" . $detail . \"\\n\";\n$send_to = '[email protected]';\n\n$headers = 'From: ' . $current_user->user_firstname . ' ' . $current_user->user_lastname . ' <[email protected]>' . \"\\r\\n\";\n\nif (wp_mail($send_to, $email_subject, $message, $headers)) {\n\n wp_redirect(admin_url('admin.php?page=contact-page&msg=success'));\n\n exit();\n} else {\n\n wp_redirect(admin_url('admin.php?page=contact-page&msg=failed'));\n\n exit();\n}\n</code></pre>\n"
},
{
"answer_id": 231131,
"author": "Rahul Bali",
"author_id": 97618,
"author_profile": "https://wordpress.stackexchange.com/users/97618",
"pm_score": 3,
"selected": true,
"text": "<p>After fiddling around for hours, I found the problem.</p>\n\n<p>It was the form not the PHP.</p>\n\n<pre><code><div class=\"col-sm-6\">\n<input class=\"form-control\" type=\"text\" placeholder=\"ENTER DOG'S NAME\" id=\"dname\" /></div>\n<div class=\"col-sm-6\">\n<input class=\"form-control\" type=\"text\" placeholder=\"ENTER OWNER'S NAME\" id=\"name\" /></div>\n</code></pre>\n\n<p><code>id</code> attribute needs to be <code>name</code>.</p>\n\n<p><strong>Corrected</strong></p>\n\n<pre><code><div class=\"col-sm-6\">\n<input class=\"form-control\" type=\"text\" placeholder=\"ENTER DOG'S NAME\" name=\"dname\" /></div>\n<div class=\"col-sm-6\">\n<input class=\"form-control\" type=\"text\" placeholder=\"ENTER OWNER'S NAME\" name=\"name\" /></div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 231158,
"author": "Tyler Burden",
"author_id": 97641,
"author_profile": "https://wordpress.stackexchange.com/users/97641",
"pm_score": 1,
"selected": false,
"text": "<p>YIKESSSSSS. There is a lot of things wrong.</p>\n\n<ol>\n<li><p>You must sanitize $_POST data or very very bad things will happen...</p></li>\n<li><p>Its best to use single quotes for strings in WordPress</p></li>\n<li><p>Spacing and indentation does not follow best practices.</p></li>\n<li><p>Your not doing anything with $_POST['name'] ???</p></li>\n<li><p>Your calling $_POST[\"email\"] but not passing it through the example form which will result in undefined variable errors ( USE WP DEBUG !!! MAKE IT TRUE )</p></li>\n<li><p>Its important to check all $_POST values not just 1 because someone can manipulate the form or a spammer could send email without the form missing a POST value causing undefined variable errors again.</p></li>\n<li><p>wp_mail should have a semi colon at the end</p></li>\n<li><p>Your missing a closing bracket, the PHP would never work.</p></li>\n<li><p>The else is not needed</p></li>\n<li><p>Your better off using wp_die if there is form tampering. If you don't want bad UX for the users then just use the required HTML tag in the input fields.</p></li>\n<li><p>No need for closing divs after input fields</p></li>\n<li><p>Best to use css and native bootstrap to handle the uppercase letters.</p></li>\n</ol>\n\n<p>the php</p>\n\n<pre><code><?php \n\nif ( isset( $_POST[\"button_pressed\"] ) ) {\n // Checking For Blank Fields..\n if ( empty( $_POST['dname'] ) || empty( $_POST['name'] ) ) {\n wp_die( __( 'Please fill out all the fields next time.', 'your-text-domain' ) );\n }\n $message = sanitize_text_field( $_POST['dname'] );\n // $email = sanitize_email( $_POST[\"email\"] );\n $name = sanitize_text_field( $_POST['name'] );\n $headers = 'From:' . \"\\r\\n\"; // Sender's Email\n $headers .= 'Cc:' . \"\\r\\n\"; // Carbon copy to Sender\n // Send mail\n wp_mail( 'PRIVATE-EMAIL-ADDRESS', $subject, $message, $headers );\n // Show Message and hide the form\n _e( 'Your mail has been sent successfully ! Thank you for your feedback.', 'your-text-domain' ); \n echo '<style>#contact-form{ display: none; }</style>';\n}\n\n?>\n</code></pre>\n\n<p>and the html markup</p>\n\n<pre><code><form action=\"\" id=\"contact-form\" method=\"post\">\n <div class=\"row\">\n <div class=\"form-group\">\n <div class=\"col-sm-6\">\n <input class=\"form-control text-uppercase\" type=\"text\" placeholder=\"<?php _e( 'Enter dogs\\'S name', 'your-text-domain' ); ?>\" name=\"dname\" required>\n <div class=\"col-sm-6\">\n <input class=\"form-control text-uppercase\" type=\"text\" placeholder=\"<?php _e( 'Enter owner\\'s name', 'your-text-domain' ); ?>\" name=\"name\" required>\n </div>\n </div>\n </div>\n <input type=\"submit\" value=\"SUBMIT\" />\n <input type=\"hidden\" name=\"button_pressed\" value=\"1\" />\n</form>\n</code></pre>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97618/"
] |
I have used `WP-Mail-SMTP` to setup the mailer on my WordPress installation.
I have tested it by sending email to my private mail.
I am now trying to send the form data using wp\_mail() function[WP].
Below is the code.
```
<?php
if(isset($_POST["button_pressed"])){
// Checking For Blank Fields..
if($_POST["dname"]==""){
echo "Fill All Fields..";
}
else {
$email=$_POST['email'];
$message = $_POST['dname'];
$headers = 'From:' . "\r\n"; // Sender's Email
$headers .= 'Cc:' . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
// $message = wordwrap($message, 70);
wp_mail("PRIVATE-EMAIL-ADDRESS", $subject, $message, $headers)
echo "Your mail has been sent successfully ! Thank you for your feedback";
}
?>
```
HTML form
```
<form>
<div class="row">
<div class="form-group">
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER DOG'S NAME" id="dname" /></div>
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" id="name" /></div>
</div>
</div>
<input type="submit" value="SUBMIT" />
<input type="hidden" name="button_pressed" value="1" />
</form>
```
I have tried many tutorials, but none helped.
Your comments and suggestions will be very helpful to me.
Thanks for your time.
|
After fiddling around for hours, I found the problem.
It was the form not the PHP.
```
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER DOG'S NAME" id="dname" /></div>
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" id="name" /></div>
```
`id` attribute needs to be `name`.
**Corrected**
```
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER DOG'S NAME" name="dname" /></div>
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" name="name" /></div>
</div>
```
|
231,125 |
<p>If set <code>show_ui</code> <code>false</code>, this hide the taxonomy meta box and admin menu link both, how to hide only meta box?</p>
<pre><code>$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wheel' ),
);
register_taxonomy( 'wheel', array( 'product' ), $args );
</code></pre>
|
[
{
"answer_id": 231174,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 4,
"selected": true,
"text": "<p>You're looking for the <code>meta_box_cb</code> argument.</p>\n\n<pre><code>$args = array(\n 'hierarchical' => true,\n 'labels' => $labels,\n 'show_ui' => false,\n 'show_admin_column' => false,\n 'show_in_menu' => true,\n 'show_in_nav_menus' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'wheel' ),\n\n 'meta_box_cb' => false,\n);\n\nregister_taxonomy( 'wheel', array( 'product' ), $args );\n</code></pre>\n\n<p>You can also define a custom callback function for displaying your own metabox if you'd like. Refer to the <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"noreferrer\">documentation for register_taxonomy()</a>.</p>\n"
},
{
"answer_id": 231178,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 0,
"selected": false,
"text": "<p>i registered the taxonomy without showing any of the UI element</p>\n\n<pre><code>add_action( 'init', 'kia_register_featured_tax', 0 );\n\nfunction kia_register_featured_tax(){\n if(!taxonomy_exists('portfolio_featured')){\n $labels = array(\n 'name' => _x( 'Featured', $this->plugin_domain ),\n 'singular_name' => _x( 'Featured', $this->plugin_domain ) \n );\n\n $args = array(\n 'labels' => $labels,\n 'rewrite' => array( 'slug' => 'portfolio-featured' ),\n 'query_var' => true,\n 'public' => true,\n 'show_ui' => false,\n 'show_tagcloud' => false,\n 'show_in_nav_menus' => false,\n );\n register_taxonomy( 'portfolio_featured', array( 'portfolio' ), $args );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 334031,
"author": "Daniel Flippance",
"author_id": 162658,
"author_profile": "https://wordpress.stackexchange.com/users/162658",
"pm_score": 0,
"selected": false,
"text": "<p>To clarify the answer from @NateWr, you need to set <code>show_ui</code> to <code>true</code>, set <code>show_in_menu</code> to <code>true</code> and set <code>meta_box_cb</code> to <code>false</code>:</p>\n\n<pre><code>$args = array(\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'meta_box_cb' => false,\n //Plus anything else you need...\n);\n\nregister_taxonomy( 'wheel', array( 'product' ), $args );\n</code></pre>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231125",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97619/"
] |
If set `show_ui` `false`, this hide the taxonomy meta box and admin menu link both, how to hide only meta box?
```
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wheel' ),
);
register_taxonomy( 'wheel', array( 'product' ), $args );
```
|
You're looking for the `meta_box_cb` argument.
```
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wheel' ),
'meta_box_cb' => false,
);
register_taxonomy( 'wheel', array( 'product' ), $args );
```
You can also define a custom callback function for displaying your own metabox if you'd like. Refer to the [documentation for register\_taxonomy()](https://developer.wordpress.org/reference/functions/register_taxonomy/).
|
231,130 |
<p>Looking at <a href="https://codex.wordpress.org/Function_Reference/human_time_diff" rel="nofollow">https://codex.wordpress.org/Function_Reference/human_time_diff</a></p>
<p>I'm using an English version of Wordpress.</p>
<p>In my theme template, I would like to define custom text of min, hour, day, week, month, year in Chinese using <code>human_time_diff()</code> when looping through posts.</p>
<p>According to the instruction in the Codex documentation:</p>
<pre><code><?php
printf( _x( '%s ago', '%s = human-readable time difference',
'your-text-domain' ), human_time_diff( get_the_time( 'U' ),
current_time( 'timestamp' ) ) );
?>
</code></pre>
<p>I still don't know how to make the implementation to do the swap using the code above. eg.</p>
<pre><code>min -> 分鐘
hour -> 小時
dat -> 天
week -> 週
month -> 月
year -> 年
</code></pre>
<p><code>ago</code> part should be straight forward.</p>
<p>Is there an example that can demonstrate how it works?</p>
<p>Also, do I need to worry about plurals in English?</p>
|
[
{
"answer_id": 231176,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>If you check out the source of <code>human_time_diff</code>:</p>\n\n<pre><code>if ( $diff < HOUR_IN_SECONDS ) {\n $mins = round( $diff / MINUTE_IN_SECONDS );\n if ( $mins <= 1 )\n $mins = 1;\n /* translators: min=minute */\n $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );\n} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {\n $hours = round( $diff / HOUR_IN_SECONDS );\n if ( $hours <= 1 )\n $hours = 1;\n $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );\n} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {\n $days = round( $diff / DAY_IN_SECONDS );\n if ( $days <= 1 )\n $days = 1;\n $since = sprintf( _n( '%s day', '%s days', $days ), $days );\n} elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {\n $weeks = round( $diff / WEEK_IN_SECONDS );\n if ( $weeks <= 1 )\n $weeks = 1;\n $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );\n} elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {\n $months = round( $diff / MONTH_IN_SECONDS );\n if ( $months <= 1 )\n $months = 1;\n $since = sprintf( _n( '%s month', '%s months', $months ), $months );\n} elseif ( $diff >= YEAR_IN_SECONDS ) {\n $years = round( $diff / YEAR_IN_SECONDS );\n if ( $years <= 1 )\n $years = 1;\n $since = sprintf( _n( '%s year', '%s years', $years ), $years );\n}\n</code></pre>\n\n<p>As you can see, just translate the <code>%s min</code>, <code>%s mins</code> etc. strings.</p>\n"
},
{
"answer_id": 231343,
"author": "KDX",
"author_id": 92505,
"author_profile": "https://wordpress.stackexchange.com/users/92505",
"pm_score": 1,
"selected": true,
"text": "<p>The full solution that works for me without modifying the Wordpress core is to clone the <code>human_time_diff()</code> function and place it inside <code>functions.php</code> as a renamed <code>human_time_diff_chinese()</code>, then swap all occurrence of <code>human_time_diff()</code> function with this new <code>human_time_diff_chinese()</code> function.</p>\n\n<pre><code>function human_time_diff_chinese( $from, $to = '' ) {\n if ( empty( $to ) ) {\n $to = time();\n }\n\n $diff = (int) abs( $to - $from );\n\n if ( $diff < HOUR_IN_SECONDS ) {\n $mins = round( $diff / MINUTE_IN_SECONDS );\n if ( $mins <= 1 )\n $mins = 1;\n /* translators: min=minute */\n $since = sprintf( _n( '%s 分鐘', '%s 分鐘', $mins ), $mins );\n } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {\n $hours = round( $diff / HOUR_IN_SECONDS );\n if ( $hours <= 1 )\n $hours = 1;\n $since = sprintf( _n( '%s 小時', '%s 小時', $hours ), $hours );\n } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {\n $days = round( $diff / DAY_IN_SECONDS );\n if ( $days <= 1 )\n $days = 1;\n $since = sprintf( _n( '%s 天', '%s 天', $days ), $days );\n } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {\n $weeks = round( $diff / WEEK_IN_SECONDS );\n if ( $weeks <= 1 )\n $weeks = 1;\n $since = sprintf( _n( '%s 週', '%s 週', $weeks ), $weeks );\n } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {\n $months = round( $diff / MONTH_IN_SECONDS );\n if ( $months <= 1 )\n $months = 1;\n $since = sprintf( _n( '%s 個月', '%s 個月', $months ), $months );\n } elseif ( $diff >= YEAR_IN_SECONDS ) {\n $years = round( $diff / YEAR_IN_SECONDS );\n if ( $years <= 1 )\n $years = 1;\n $since = sprintf( _n( '%s 年', '%s 年', $years ), $years );\n }\n\n return apply_filters( 'human_time_diff_chinese', $since, $diff, $from, $to );\n}\n</code></pre>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92505/"
] |
Looking at <https://codex.wordpress.org/Function_Reference/human_time_diff>
I'm using an English version of Wordpress.
In my theme template, I would like to define custom text of min, hour, day, week, month, year in Chinese using `human_time_diff()` when looping through posts.
According to the instruction in the Codex documentation:
```
<?php
printf( _x( '%s ago', '%s = human-readable time difference',
'your-text-domain' ), human_time_diff( get_the_time( 'U' ),
current_time( 'timestamp' ) ) );
?>
```
I still don't know how to make the implementation to do the swap using the code above. eg.
```
min -> 分鐘
hour -> 小時
dat -> 天
week -> 週
month -> 月
year -> 年
```
`ago` part should be straight forward.
Is there an example that can demonstrate how it works?
Also, do I need to worry about plurals in English?
|
The full solution that works for me without modifying the Wordpress core is to clone the `human_time_diff()` function and place it inside `functions.php` as a renamed `human_time_diff_chinese()`, then swap all occurrence of `human_time_diff()` function with this new `human_time_diff_chinese()` function.
```
function human_time_diff_chinese( $from, $to = '' ) {
if ( empty( $to ) ) {
$to = time();
}
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s 分鐘', '%s 分鐘', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s 小時', '%s 小時', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s 天', '%s 天', $days ), $days );
} elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s 週', '%s 週', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
$months = round( $diff / MONTH_IN_SECONDS );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s 個月', '%s 個月', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s 年', '%s 年', $years ), $years );
}
return apply_filters( 'human_time_diff_chinese', $since, $diff, $from, $to );
}
```
|
231,137 |
<p>I'm very new to this API, in fact I've only spent couple hours on it so far. I've done my research but cannot find anything about it...</p>
<p>The issue is, I can't seem to get the featured image of a post. The JSON returns <code>"featured_media: 0"</code>.</p>
<pre><code>getPosts: function() {
var burl = "http://www.example.com/wp-json/wp/v2/posts";
var dataDiv = document.getElementById('cards');
$.ajax({
url: burl,
data: data,
type: 'GET',
async: false,
processData: false,
beforeSend: function (xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function (data) {
console.log(data);
//question: data->featured_image: 0?!
var theUl = document.getElementById('cards');
for (var key in data) {
//data[key]['']...
//doing my stuff here
}
},
error: function(e) {
console.log('Error: '+e);
}
});
}
</code></pre>
<p>I have definitely, set a featured image on the post but data returns:</p>
<p><a href="https://i.stack.imgur.com/ZGzzL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZGzzL.png" alt="featured media?"></a></p>
<p>Any help will be appreciated.</p>
|
[
{
"answer_id": 231138,
"author": "Michael Cropper",
"author_id": 91911,
"author_profile": "https://wordpress.stackexchange.com/users/91911",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at a plugin called <a href=\"https://wordpress.org/plugins/better-rest-api-featured-images/\" rel=\"noreferrer\">Better REST API Featured Image</a>. It adds the featured image URL to the original API response.</p>\n"
},
{
"answer_id": 268706,
"author": "Eslam Mahmoud",
"author_id": 120840,
"author_profile": "https://wordpress.stackexchange.com/users/120840",
"pm_score": 8,
"selected": true,
"text": "<p>You can get it without plugins by adding <code>_embed</code>as param to your query </p>\n\n<pre><code>/?rest_route=/wp/v2/posts&_embed\n/wp-json/wp/v2/posts?_embed\n</code></pre>\n"
},
{
"answer_id": 292751,
"author": "RobK",
"author_id": 135976,
"author_profile": "https://wordpress.stackexchange.com/users/135976",
"pm_score": 3,
"selected": false,
"text": "<p>You can get the name of the image with this path:</p>\n\n<p>array_name._embedded['wp:featuredmedia']['0'].source_url</p>\n"
},
{
"answer_id": 315461,
"author": "lakewood",
"author_id": 122711,
"author_profile": "https://wordpress.stackexchange.com/users/122711",
"pm_score": 2,
"selected": false,
"text": "<p>I made a shortcut to my image by adding it directly to the API response.</p>\n\n<hr>\n\n<pre><code>//Add in functions.php, this hook is for my 'regions' post type\nadd_action( 'rest_api_init', 'create_api_posts_meta_field' );\n\nfunction create_api_posts_meta_field() {\n register_rest_field( 'regions', 'group', array(\n 'get_callback' => 'get_post_meta_for_api',\n 'schema' => null,\n )\n );\n}\n</code></pre>\n\n<hr>\n\n<pre><code>//Use the post ID to query the image and add it to your payload\nfunction get_post_meta_for_api( $object ) {\n $post_id = $object['id'];\n $post_meta = get_post_meta( $post_id );\n $post_image = get_post_thumbnail_id( $post_id ); \n $post_meta[\"group_image\"] = wp_get_attachment_image_src($post_image)[0];\n\n return $post_meta;\n}\n</code></pre>\n"
},
{
"answer_id": 317331,
"author": "Null TX",
"author_id": 152713,
"author_profile": "https://wordpress.stackexchange.com/users/152713",
"pm_score": 4,
"selected": false,
"text": "<p>I would NOT use the better rest API plugin. It did add featured images to the rest api but it also broke it.</p>\n\n<p>This is the simplest solution I was able to find that actually worked. Add the following code to your functions.php:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\nfunction post_featured_image_json( $data, $post, $context ) {\n $featured_image_id = $data->data['featured_media']; // get featured image id\n $featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'original' ); // get url of the original size\n\n if( $featured_image_url ) {\n $data->data['featured_image_url'] = $featured_image_url[0];\n }\n\n return $data;\n}\nadd_filter( 'rest_prepare_post', 'post_featured_image_json', 10, 3 );\n\n</code></pre>\n"
},
{
"answer_id": 371147,
"author": "MAM.AASIM",
"author_id": 191681,
"author_profile": "https://wordpress.stackexchange.com/users/191681",
"pm_score": 1,
"selected": false,
"text": "<p>Try following way\n....................</p>\n<p>URL: <code>/wp-json/wp/v2/posts?_embed</code></p>\n<p>image: <code>json["_embedded"]["wp:featuredmedia"][0]["source_url"],</code></p>\n<p>It's working fine.try</p>\n"
},
{
"answer_id": 402773,
"author": "Jay Pokale",
"author_id": 219311,
"author_profile": "https://wordpress.stackexchange.com/users/219311",
"pm_score": 0,
"selected": false,
"text": "<p>I installed the Yoast SEO plugin and found that the featured image URL is available in that.\nAfter\nURL: <code>/wp-json/wp/v2/posts?_embed</code></p>\n<p>You can find featured image in: <code>yoast_head_json > robots > og_image > url</code></p>\n"
},
{
"answer_id": 402880,
"author": "Jay Pokale",
"author_id": 219311,
"author_profile": "https://wordpress.stackexchange.com/users/219311",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li><p>Install Yoast SEO plugin</p>\n</li>\n<li><p>Get data from wp rest api to javascript</p>\n<pre><code> async function fetchPosts() {\n const responce = await fetch('https://example.com/wp-json/wp/v2/posts');\n return responce.json();}\n</code></pre>\n</li>\n<li><p>I am displaying 10 images in HTML (I used ID = posts in .html file)</p>\n<pre><code> (async () => {\n var images = '';\n for (var i = 0; i < 10; i++) {\n var obj = `<img src = '${(await fetchPosts())[i].yoast_head_json.og_image[0].url}' width="500"></img>`;\n images += obj;\n document.getElementById('posts').innerHTML = `${images}`\n }})()\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 403792,
"author": "GNELEZIE",
"author_id": 220351,
"author_profile": "https://wordpress.stackexchange.com/users/220351",
"pm_score": 2,
"selected": false,
"text": "<p>Paste this code in your theme's <code>functions.php</code> file and use this key for the featured image: <code>featured_image_url</code></p>\n<pre><code>function post_featured_image_json( $data, $post, $context ) {\n $featured_image_id = $data->data['featured_media']; // get featured image id\n $featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'original' ); // get url of the original size\n\n if( $featured_image_url ) {\n $data->data['featured_image_url'] = $featured_image_url[0];\n }\n\n return $data;\n}\nadd_filter( 'rest_prepare_post', 'post_featured_image_json', 10, 3 );\n</code></pre>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97623/"
] |
I'm very new to this API, in fact I've only spent couple hours on it so far. I've done my research but cannot find anything about it...
The issue is, I can't seem to get the featured image of a post. The JSON returns `"featured_media: 0"`.
```
getPosts: function() {
var burl = "http://www.example.com/wp-json/wp/v2/posts";
var dataDiv = document.getElementById('cards');
$.ajax({
url: burl,
data: data,
type: 'GET',
async: false,
processData: false,
beforeSend: function (xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function (data) {
console.log(data);
//question: data->featured_image: 0?!
var theUl = document.getElementById('cards');
for (var key in data) {
//data[key]['']...
//doing my stuff here
}
},
error: function(e) {
console.log('Error: '+e);
}
});
}
```
I have definitely, set a featured image on the post but data returns:
[](https://i.stack.imgur.com/ZGzzL.png)
Any help will be appreciated.
|
You can get it without plugins by adding `_embed`as param to your query
```
/?rest_route=/wp/v2/posts&_embed
/wp-json/wp/v2/posts?_embed
```
|
231,144 |
<p>Basically a post is an event therefor will be displayed once or twice, depending on meta key.
Every post has at least two meta keys <code>$start_time_1</code> and <code>$end_time_1</code>. Let's say i have two posts, title: "Radio Show" and "TV Show". </p>
<pre><code>Radio Show - start @ 2016-07-01 12:00
TV Show - start @ 2016-07-01 15:00
</code></pre>
<p>My code below, works fine. But what if i add another start time like <code>$start_time_2</code>and <code>$end_time_2</code> and all post sorted by start time.
Just like this:</p>
<pre><code>Radio Show - start @ 2016-07-01 12:30
TV Show - start @ 2016-07-01 15:30
TV Show - start @ 2016-07-02 21:00
Radio Show - start @ 2016-02-01 23:00
</code></pre>
<p>This the query i'using but i cant make to show the post twice.</p>
<pre><code>$start_time_1 = '2016-07-01 12:30';
$end_time_1 = '2016-07-01 14:30';
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => $end_time_1, // if the time() is greater than end time dont display post
'value' => date('Y-m-d H:i'),
'compare' => '>='
)),
'meta_key' => $start_time_1, // for sorting posts
'orderby' => array(
'meta_value' => 'ASC',
'post_date' => 'ASC',
),
'order' => 'ASC',
);
</code></pre>
|
[
{
"answer_id": 231153,
"author": "Samuel E. Cerezo",
"author_id": 97635,
"author_profile": "https://wordpress.stackexchange.com/users/97635",
"pm_score": 0,
"selected": false,
"text": "<p>What about using this?</p>\n\n<pre>\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => -1,\n 'post_status' => 'publish',\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => $end_time_1,\n 'value' => date('Y-m-d H:i'),\n 'compare' => '>='\n ),\n array(\n 'key' => $end_time_2,\n 'value' => date('Y-m-d H:i'),\n 'compare' => '>='\n )\n ),\n 'meta_key' => $start_time_1,\n 'orderby' => array( \n 'meta_value' => 'ASC', \n 'post_date' => 'ASC',\n ),\n 'order' => 'ASC',\n);\n</pre>\n\n<p>I think you can use nested relationships to do a more comprehensive query.</p>\n"
},
{
"answer_id": 231171,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 1,
"selected": false,
"text": "<p>As Tim Malone said, WP_Query isn't going to return multiple copies of the same post in its result set. I think you have a design problem and I would suggest you use parent/child posts rather than post meta to accomplish what you want.</p>\n\n<p>The following is one approach to doing this. First, register both post types:</p>\n\n<pre><code>// The parent event type\n// There will be one of these for Radio Show and TV Show\nregister_post_type( 'event', $args );\n\n// A non-public event type for each \"occurrence\" of an event\n// There will be two of these for each Radio Show and TV Show\nregister_post_type( 'event_occurrence', array(\n // add all of your usual $args and then set public to false\n 'public' => false,\n) );\n</code></pre>\n\n<p>Then, when saving your <code>event</code> post, don't save the start/end times as post meta on that post object. Instead use those dates to create <code>event_occurrence</code> posts for each occurrence, with the start and end times saved there.</p>\n\n<pre><code>$occurrence_id = wp_insert_post( array(\n // add all of your occurrence details and then set the parent\n // to the `event` post that's being saved\n 'post_parent' => <event_post_id>,\n\n // Set the post date to the start time for efficient ordering\n 'post_date' => $start_time,\n) );\n\n// Save the end time as post meta\n// Save it as a Unix timestamp so that we can compare it in the query\nupdate_post_meta( $occurrence_id, 'end_time', strtotime( $end_time ) );\n</code></pre>\n\n<p>Now you should have the following posts in the database:</p>\n\n<pre><code>Radio Show\n Radio Show Instance 1\n Radio Show Instance 2\nTV Show\n TV Show Instance 1\n TV Show Instance 2\n</code></pre>\n\n<p>You can then query the occurrences like this:</p>\n\n<pre><code>$args = array(\n\n // Only fetch occurrences\n 'post_type' => 'event_occurrence',\n\n // Retrieve only future occurrences\n 'date_query' => array(\n array(\n 'after' => 'now',\n )\n ),\n\n // use a reasonably high posts_per_page instead of -1\n // otherwise you could accidentally cripple a site\n // with an expensive query\n 'posts_per_page' => 500,\n\n 'post_status' => 'publish',\n\n 'meta_query' => array(\n array(\n 'key' => 'end_time',\n 'value' => time(),\n 'compare' => '>='\n ),\n ),\n\n // They'll be ordered by start date.\n // ASC starts with earliest first\n 'order' => 'ASC',\n);\n</code></pre>\n\n<p>Our loop will now contain four posts:</p>\n\n<pre><code>Radio Show Instance 1\nRadio Show Instance 2\nTV Show Instance 1\nTV Show Instance 2\n</code></pre>\n\n<p>So while you're looping through the occurrences, you can access the parent post of each occurrence to get the overall event data. You can do this with a simple function:</p>\n\n<pre><code>$parent_event_id = wp_get_post_parent_id( get_the_ID() );\n</code></pre>\n\n<p>However, this will result in a lot of extra queries to the database which will effect performance. Instead, I'd recommend you run a separate query for the primary <code>event</code> posts, and then pull them from those results, so you're only making one additional query to the database:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'event',\n 'date_query' => array(\n array(\n 'after' => 'now',\n )\n ),\n 'posts_per_page' => 500,\n 'post_status' => 'publish',\n 'meta_query' => array(\n array(\n 'key' => 'end_time',\n 'value' => time(),\n 'compare' => '>='\n ),\n ),\n 'order' => 'ASC',\n);\n$events = new WP_Query( $args );\n</code></pre>\n\n<p>So your $occurrences loop would look like this:</p>\n\n<pre><code>$occurrences = new WP_Query( $occurrences_args );\nwhile( $occurrences->have_posts() ) {\n $occurrences->the_post();\n\n // Get the parent event data\n $parent_event_id = wp_get_post_parent_id( get_the_ID() );\n $parent_event = null;\n foreach ( $events->posts as $post ) {\n if ( $post->ID == $parent_event_id ) {\n $parent_event = $post;\n break;\n }\n }\n\n // Now you can use the loop to access the\n // occurrence data and use $parent_event to\n // access the overall event data\n}\n</code></pre>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97628/"
] |
Basically a post is an event therefor will be displayed once or twice, depending on meta key.
Every post has at least two meta keys `$start_time_1` and `$end_time_1`. Let's say i have two posts, title: "Radio Show" and "TV Show".
```
Radio Show - start @ 2016-07-01 12:00
TV Show - start @ 2016-07-01 15:00
```
My code below, works fine. But what if i add another start time like `$start_time_2`and `$end_time_2` and all post sorted by start time.
Just like this:
```
Radio Show - start @ 2016-07-01 12:30
TV Show - start @ 2016-07-01 15:30
TV Show - start @ 2016-07-02 21:00
Radio Show - start @ 2016-02-01 23:00
```
This the query i'using but i cant make to show the post twice.
```
$start_time_1 = '2016-07-01 12:30';
$end_time_1 = '2016-07-01 14:30';
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => $end_time_1, // if the time() is greater than end time dont display post
'value' => date('Y-m-d H:i'),
'compare' => '>='
)),
'meta_key' => $start_time_1, // for sorting posts
'orderby' => array(
'meta_value' => 'ASC',
'post_date' => 'ASC',
),
'order' => 'ASC',
);
```
|
As Tim Malone said, WP\_Query isn't going to return multiple copies of the same post in its result set. I think you have a design problem and I would suggest you use parent/child posts rather than post meta to accomplish what you want.
The following is one approach to doing this. First, register both post types:
```
// The parent event type
// There will be one of these for Radio Show and TV Show
register_post_type( 'event', $args );
// A non-public event type for each "occurrence" of an event
// There will be two of these for each Radio Show and TV Show
register_post_type( 'event_occurrence', array(
// add all of your usual $args and then set public to false
'public' => false,
) );
```
Then, when saving your `event` post, don't save the start/end times as post meta on that post object. Instead use those dates to create `event_occurrence` posts for each occurrence, with the start and end times saved there.
```
$occurrence_id = wp_insert_post( array(
// add all of your occurrence details and then set the parent
// to the `event` post that's being saved
'post_parent' => <event_post_id>,
// Set the post date to the start time for efficient ordering
'post_date' => $start_time,
) );
// Save the end time as post meta
// Save it as a Unix timestamp so that we can compare it in the query
update_post_meta( $occurrence_id, 'end_time', strtotime( $end_time ) );
```
Now you should have the following posts in the database:
```
Radio Show
Radio Show Instance 1
Radio Show Instance 2
TV Show
TV Show Instance 1
TV Show Instance 2
```
You can then query the occurrences like this:
```
$args = array(
// Only fetch occurrences
'post_type' => 'event_occurrence',
// Retrieve only future occurrences
'date_query' => array(
array(
'after' => 'now',
)
),
// use a reasonably high posts_per_page instead of -1
// otherwise you could accidentally cripple a site
// with an expensive query
'posts_per_page' => 500,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'end_time',
'value' => time(),
'compare' => '>='
),
),
// They'll be ordered by start date.
// ASC starts with earliest first
'order' => 'ASC',
);
```
Our loop will now contain four posts:
```
Radio Show Instance 1
Radio Show Instance 2
TV Show Instance 1
TV Show Instance 2
```
So while you're looping through the occurrences, you can access the parent post of each occurrence to get the overall event data. You can do this with a simple function:
```
$parent_event_id = wp_get_post_parent_id( get_the_ID() );
```
However, this will result in a lot of extra queries to the database which will effect performance. Instead, I'd recommend you run a separate query for the primary `event` posts, and then pull them from those results, so you're only making one additional query to the database:
```
$args = array(
'post_type' => 'event',
'date_query' => array(
array(
'after' => 'now',
)
),
'posts_per_page' => 500,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'end_time',
'value' => time(),
'compare' => '>='
),
),
'order' => 'ASC',
);
$events = new WP_Query( $args );
```
So your $occurrences loop would look like this:
```
$occurrences = new WP_Query( $occurrences_args );
while( $occurrences->have_posts() ) {
$occurrences->the_post();
// Get the parent event data
$parent_event_id = wp_get_post_parent_id( get_the_ID() );
$parent_event = null;
foreach ( $events->posts as $post ) {
if ( $post->ID == $parent_event_id ) {
$parent_event = $post;
break;
}
}
// Now you can use the loop to access the
// occurrence data and use $parent_event to
// access the overall event data
}
```
|
231,152 |
<p>I am very well aware of <code>how to make multiple sidebars</code>. But I believe my way is not proper way of adding multiple sidebars.</p>
<p><strong>This is how I add multiple sidebars</strong></p>
<p>If I simply wants to create a sidebar then I use sidebar.php file. BUT if I want to use another sidebar then I have to create another php file
like <code>sidebar-new.php</code>. Then call this file as </p>
<pre><code> <?php
get_sidebar('new');
?>
</code></pre>
<p>That mean if I want to create 4 sidebar then I have to make 4 php files!</p>
<p>BUT I have seen many themes (In wordpress market) that provide many sidebars but they contains only one php file for sidebar (sidebar.php)!
How do they do that? I have learned about making sidebars from google earlier but in search I only get the results that I am using right now (create multiple files for multiple sidebars).</p>
<p>So how can I create multiple sidebar without making Multiple php files!!???</p>
|
[
{
"answer_id": 231160,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>You can differentiate between sidebars <strong>inside</strong> <code>sidebar.php</code>. I don't know what your purpose is, but let's suppose you want different sidebars on single posts/pages and other pages.</p>\n\n<p>In your <code>functions.php</code> you would register two sidebars with id's <code>singular</code> and <code>default</code> in the usual way with <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow\"><code>register_sidebar</code></a>.</p>\n\n<p>Then in <code>sidebar.php</code> you would include something like</p>\n\n<pre><code>if (is_singular) {dynamic_sidebar('singular');}\nelse {dynamic_sidebar('default');}\n</code></pre>\n\n<p>Of course, there are many ways to vary on this. You can display different sidebars depending on category or maybe no sidebar at all on a special page template called 'one-column'.</p>\n"
},
{
"answer_id": 231167,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 3,
"selected": false,
"text": "<p>Defining new sidebar with in your functions.php</p>\n\n<pre><code><?php\n\nif ( function_exists('register_sidebar') ) {\n\n register_sidebar(array(\n 'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</li>',\n 'before_title' => '<h2 class=\"widgettitle\">',\n 'after_title' => '</h2>'\n ));\n\n}?>\n</code></pre>\n\n<p>Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.</p>\n\n<pre><code><?php\n\nif ( function_exists('register_sidebar') ) {\n\n register_sidebar(array(\n 'name' => 'sidebar 1',\n 'before_widget' => '<div id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2>',\n 'after_title' => '</h2>'\n ));\n\n register_sidebar(array(\n 'name' => 'footer sidebar 1',\n 'before_widget' => '<div id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2>',\n 'after_title' => '</h2>'\n ));\n\n}?>\n</code></pre>\n\n<p>Adding new sidebar to your template</p>\n\n<p>Within your sidebar.php file, change the call to your existing sidebar to include its name that you defined within the functions.php file earlier.</p>\n\n<pre><code><?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar 1') ) : ?>\n\n <h2>Articles by month</h2>\n <ul>\n <?php wp_get_archives('title_li=&type=monthly'); ?>\n </ul>\n <h2>Categories</h2>\n <ul>\n <?php wp_list_categories('show_count=0&title_li='); ?>\n </ul>\n\n<?php endif; ?>\n</code></pre>\n\n<p>To add your new sidebar, you can either copy the above code or you can simply copy the following lines. Add these lines to wherever you’d like your new widgets to appear. In this example you can see from the name that I’m placing mine in the footer of my website. As before, don’t forget to specify the correct sidebar name. In the above code, the html that appears between the php statements is what will appear when there are no widgets added to your sidebar. This ‘default’ code can obviously be modified to suit your theme. In the following code, since there is no extra html, nothing will be displayed unless a widget has been added into the sidebar within your WordPress dashboard.</p>\n\n<pre><code><?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer sidebar 1') ) : ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 278745,
"author": "Rachit",
"author_id": 126961,
"author_profile": "https://wordpress.stackexchange.com/users/126961",
"pm_score": 0,
"selected": false,
"text": "<p>You can create multiple sidebar using vc or wordpress editor by <a href=\"https://codecanyon.net/item/custom-sidebar-visual-editor-wordpress-plugin/17329853\" rel=\"nofollow noreferrer\">https://codecanyon.net/item/custom-sidebar-visual-editor-wordpress-plugin/17329853</a></p>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81621/"
] |
I am very well aware of `how to make multiple sidebars`. But I believe my way is not proper way of adding multiple sidebars.
**This is how I add multiple sidebars**
If I simply wants to create a sidebar then I use sidebar.php file. BUT if I want to use another sidebar then I have to create another php file
like `sidebar-new.php`. Then call this file as
```
<?php
get_sidebar('new');
?>
```
That mean if I want to create 4 sidebar then I have to make 4 php files!
BUT I have seen many themes (In wordpress market) that provide many sidebars but they contains only one php file for sidebar (sidebar.php)!
How do they do that? I have learned about making sidebars from google earlier but in search I only get the results that I am using right now (create multiple files for multiple sidebars).
So how can I create multiple sidebar without making Multiple php files!!???
|
Defining new sidebar with in your functions.php
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
));
}?>
```
Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => 'sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
register_sidebar(array(
'name' => 'footer sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
}?>
```
Adding new sidebar to your template
Within your sidebar.php file, change the call to your existing sidebar to include its name that you defined within the functions.php file earlier.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar 1') ) : ?>
<h2>Articles by month</h2>
<ul>
<?php wp_get_archives('title_li=&type=monthly'); ?>
</ul>
<h2>Categories</h2>
<ul>
<?php wp_list_categories('show_count=0&title_li='); ?>
</ul>
<?php endif; ?>
```
To add your new sidebar, you can either copy the above code or you can simply copy the following lines. Add these lines to wherever you’d like your new widgets to appear. In this example you can see from the name that I’m placing mine in the footer of my website. As before, don’t forget to specify the correct sidebar name. In the above code, the html that appears between the php statements is what will appear when there are no widgets added to your sidebar. This ‘default’ code can obviously be modified to suit your theme. In the following code, since there is no extra html, nothing will be displayed unless a widget has been added into the sidebar within your WordPress dashboard.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer sidebar 1') ) : ?>
<?php endif; ?>
```
|
231,154 |
<p>I am new with word press and I want to show the post of a specific category on my page. The name of the category which i want to show is <code>home slider</code>. Below is the code which I have used to display all the posts <code>title</code>, <code>image</code> and <code>content</code>.</p>
<pre><code><div class="row">
<?php $myposts = get_posts( 'numberposts=6&offset=$debut' );
foreach( $myposts as $post) : setup_postdata( $post ) ?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<?php the_post_thumbnail( 'thumbnail'); ?>
<div class="caption">
<h4 class="pull-right">$94.99</h4>
<a> <?php the_title(); ?> </a>
<!--I have used this substr here to set the limit of the text, and if do not want to set the limit simply use this line of code <?php //the_content(); ?>-->
<?php echo substr(get_the_excerpt(), 0,30); ?>...
<a href="#" >read more</a>
</div>
<div class="ratings">
<p class="pull-right">18 reviews</p>
<p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</code></pre>
<p>Can please anyone edit this code so that I can show posts of the specific category which in my case is <code>home slider</code>.
Thank you.</p>
|
[
{
"answer_id": 231160,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>You can differentiate between sidebars <strong>inside</strong> <code>sidebar.php</code>. I don't know what your purpose is, but let's suppose you want different sidebars on single posts/pages and other pages.</p>\n\n<p>In your <code>functions.php</code> you would register two sidebars with id's <code>singular</code> and <code>default</code> in the usual way with <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow\"><code>register_sidebar</code></a>.</p>\n\n<p>Then in <code>sidebar.php</code> you would include something like</p>\n\n<pre><code>if (is_singular) {dynamic_sidebar('singular');}\nelse {dynamic_sidebar('default');}\n</code></pre>\n\n<p>Of course, there are many ways to vary on this. You can display different sidebars depending on category or maybe no sidebar at all on a special page template called 'one-column'.</p>\n"
},
{
"answer_id": 231167,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 3,
"selected": false,
"text": "<p>Defining new sidebar with in your functions.php</p>\n\n<pre><code><?php\n\nif ( function_exists('register_sidebar') ) {\n\n register_sidebar(array(\n 'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</li>',\n 'before_title' => '<h2 class=\"widgettitle\">',\n 'after_title' => '</h2>'\n ));\n\n}?>\n</code></pre>\n\n<p>Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.</p>\n\n<pre><code><?php\n\nif ( function_exists('register_sidebar') ) {\n\n register_sidebar(array(\n 'name' => 'sidebar 1',\n 'before_widget' => '<div id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2>',\n 'after_title' => '</h2>'\n ));\n\n register_sidebar(array(\n 'name' => 'footer sidebar 1',\n 'before_widget' => '<div id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2>',\n 'after_title' => '</h2>'\n ));\n\n}?>\n</code></pre>\n\n<p>Adding new sidebar to your template</p>\n\n<p>Within your sidebar.php file, change the call to your existing sidebar to include its name that you defined within the functions.php file earlier.</p>\n\n<pre><code><?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar 1') ) : ?>\n\n <h2>Articles by month</h2>\n <ul>\n <?php wp_get_archives('title_li=&type=monthly'); ?>\n </ul>\n <h2>Categories</h2>\n <ul>\n <?php wp_list_categories('show_count=0&title_li='); ?>\n </ul>\n\n<?php endif; ?>\n</code></pre>\n\n<p>To add your new sidebar, you can either copy the above code or you can simply copy the following lines. Add these lines to wherever you’d like your new widgets to appear. In this example you can see from the name that I’m placing mine in the footer of my website. As before, don’t forget to specify the correct sidebar name. In the above code, the html that appears between the php statements is what will appear when there are no widgets added to your sidebar. This ‘default’ code can obviously be modified to suit your theme. In the following code, since there is no extra html, nothing will be displayed unless a widget has been added into the sidebar within your WordPress dashboard.</p>\n\n<pre><code><?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer sidebar 1') ) : ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 278745,
"author": "Rachit",
"author_id": 126961,
"author_profile": "https://wordpress.stackexchange.com/users/126961",
"pm_score": 0,
"selected": false,
"text": "<p>You can create multiple sidebar using vc or wordpress editor by <a href=\"https://codecanyon.net/item/custom-sidebar-visual-editor-wordpress-plugin/17329853\" rel=\"nofollow noreferrer\">https://codecanyon.net/item/custom-sidebar-visual-editor-wordpress-plugin/17329853</a></p>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97583/"
] |
I am new with word press and I want to show the post of a specific category on my page. The name of the category which i want to show is `home slider`. Below is the code which I have used to display all the posts `title`, `image` and `content`.
```
<div class="row">
<?php $myposts = get_posts( 'numberposts=6&offset=$debut' );
foreach( $myposts as $post) : setup_postdata( $post ) ?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<?php the_post_thumbnail( 'thumbnail'); ?>
<div class="caption">
<h4 class="pull-right">$94.99</h4>
<a> <?php the_title(); ?> </a>
<!--I have used this substr here to set the limit of the text, and if do not want to set the limit simply use this line of code <?php //the_content(); ?>-->
<?php echo substr(get_the_excerpt(), 0,30); ?>...
<a href="#" >read more</a>
</div>
<div class="ratings">
<p class="pull-right">18 reviews</p>
<p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
```
Can please anyone edit this code so that I can show posts of the specific category which in my case is `home slider`.
Thank you.
|
Defining new sidebar with in your functions.php
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
));
}?>
```
Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => 'sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
register_sidebar(array(
'name' => 'footer sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
}?>
```
Adding new sidebar to your template
Within your sidebar.php file, change the call to your existing sidebar to include its name that you defined within the functions.php file earlier.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar 1') ) : ?>
<h2>Articles by month</h2>
<ul>
<?php wp_get_archives('title_li=&type=monthly'); ?>
</ul>
<h2>Categories</h2>
<ul>
<?php wp_list_categories('show_count=0&title_li='); ?>
</ul>
<?php endif; ?>
```
To add your new sidebar, you can either copy the above code or you can simply copy the following lines. Add these lines to wherever you’d like your new widgets to appear. In this example you can see from the name that I’m placing mine in the footer of my website. As before, don’t forget to specify the correct sidebar name. In the above code, the html that appears between the php statements is what will appear when there are no widgets added to your sidebar. This ‘default’ code can obviously be modified to suit your theme. In the following code, since there is no extra html, nothing will be displayed unless a widget has been added into the sidebar within your WordPress dashboard.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer sidebar 1') ) : ?>
<?php endif; ?>
```
|
231,165 |
<p>We have created a CPT which allows our customer to upload files from the admin page to a folder outside of the wp-content/uploads folder. Files are uploaded and manipulated using wp_handle_upload and wp_insert_attachment.</p>
<p>How do we prevent these files from showing in the media library? Can we filter by post type?</p>
<p>Thanks in advance for any help!</p>
<p><strong>UPDATE:</strong> here's the code we've implemented so far. New uploads are still not showing in the media library.</p>
<pre><code>/*FORCE LIST VIEW IN MEDIA LIBRARY*/
add_action('admin_init', function() {
$_GET['mode'] = 'list';
}, 100);
/*HIDE GRID BUTTON IN MEDIA LIBRARY*/
add_action('admin_head', function() {
$css = '<style type="text/css">
.view-switch .view-grid {
display: none;
}
<style>';
echo $css;
});
/*REGISTER CUSTOM TAXONOMY*/
function create_hidden_taxonomy() {
register_taxonomy(
'hidden_taxonomy',
'attachment',
array(
'label' => __( 'Hidden Taxonomy' ),
'public' => false,
'rewrite' => false,
'hierarchical' => false,
)
);
}
add_action( 'init', 'create_hidden_taxonomy' );
/*CHECK IF PARENT POST TYPE IS ASSET. IF NOT ADD 'show_in_media_library' TERM*/
function assets_add_term( $post_id, \WP_Post $p, $update ) {
if ( 'attachment' !== $p->post_type ) {
error_log("fail1");
return;
}
if ( wp_is_post_revision( $post_id ) ) {
error_log("fail2");
return;
}
if ( $post->post_parent ) {
$excluded_types = array( 'assets' );
if ( in_array( get_post_type( $p->post_parent ), $excluded_types ) ) {
error_log("fail3");
return;
}
}
$result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );
if ( !is_array( $result ) || is_wp_error( $result ) ) {
error_log("fail4");
}else{
error_log("it worked!");
}
}
add_action( 'save_post', 'assets_add_term', 10, 2 );
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY*/
function assets_load_media() {
add_action('pre_get_posts','assets_hide_media',10,1);
}
add_action( 'load-upload.php' , 'assets_load_media' );
function assets_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = get_posts('post_type=assets&posts_per_page=-1&fields=ids');
$query->set('post_parent__not_in', $excluded_cpt_ids);
//$query->set('hidden_taxonomy', 'show_in_media_library' );
}
return $query;
}
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY MODAL*/
function assets_hide_media_modal( $query = array() ){
$query['post_parent__not_in'] = $excluded_cpt_ids;
return $query;
}
add_action('ajax_query_attachments_args','assets_hide_media_modal',10,1);
</code></pre>
|
[
{
"answer_id": 231201,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 4,
"selected": true,
"text": "<p>Media items are just like posts with <strong><code>post_type = attachment</code></strong> and <strong><code>post_status = inherit</code></strong>.</p>\n\n<p>when we are on <code>upload.php</code> page, we have two views:</p>\n\n<ul>\n<li>List View</li>\n<li>Grid View</li>\n</ul>\n\n<p>Grid view is populated via JavaScript and list view is extending normal <strong><code>WP_List_Table</code></strong>.</p>\n\n<p>Since it (List view) is using normal post query we can use <strong><code>pre_get_posts</code></strong> to alter the query to hide required media items.</p>\n\n<blockquote>\n <p>How do we prevent these files from showing in the media library?<br />Can\n we filter by post type?</p>\n</blockquote>\n\n<p>We can't just filter the media items by <code>post_type</code> since media items post_type is <code>attachment</code>. What you want is to filter media items by their <strong><code>post_parent's</code></strong> post ids.</p>\n\n<pre><code>add_action( 'load-upload.php' , 'wp_231165_load_media' );\nfunction wp_231165_load_media() {\n add_action('pre_get_posts','wp_231165_hide_media',10,1);\n}\n\nfunction wp_231165_hide_media($query){\n global $pagenow;\n\n// there is no need to check for update.php as we are already hooking to it, but anyway\n if( 'upload.php' != $pagenow || !is_admin())\n return;\n\n if(is_main_query()){\n $excluded_cpt_ids = array();//find a way to get all cpt post ids\n $query->set('post_parent__not_in', $excluded_cpt_ids);\n }\n\n return $query;\n}\n</code></pre>\n\n<p>Check <a href=\"https://wordpress.stackexchange.com/questions/165900/getting-the-ids-of-a-custom-post-type/165916\">this question</a> to get id's of a certain post type.</p>\n\n<p>As @tomjnowell pointed out it works for list view but it's an expensive query.</p>\n\n<p>One thing you can do is that add some meta value while uploading and query against that meta value</p>\n"
},
{
"answer_id": 231210,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>When you create an attachment, do the following:</p>\n<ul>\n<li>If attachments parent ID is for a post with an excluded post type, do nothing</li>\n<li>If it isn't in the list of excluded post types, assign it a tag in a hidden custom taxonomy</li>\n</ul>\n<p>e.g.</p>\n<pre><code>function create_hidden_taxonomy() {\n register_taxonomy(\n 'hidden_taxonomy',\n 'attachment',\n array(\n 'label' => __( 'Hidden Attachment Taxonomy' ),\n 'public' => false, // it's hidden!\n 'rewrite' => false,\n 'hierarchical' => false,\n )\n );\n}\nadd_action( 'init', 'create_hidden_taxonomy' );\n\nfunction tomjn_add_term( $post_id, \\WP_Post $p, $update ) {\n\n if ( 'attachment' !== $p->post_type ) {\n return;\n }\n if ( wp_is_post_revision( $post_id ) ) {\n return;\n }\n if ( $p->post_parent ) {\n $excluded_types = array( 'example_post_type', 'other_post_type' );\n if ( in_array( get_post_type( $p->post_parent ), $excluded_types ) ) {\n return;\n }\n }\n $result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );\n if ( !is_array( $result ) || is_wp_error( $result ) ) {\n wp_die( "Error setting up terms") ;\n }\n}\nadd_action( 'save_post', 'tomjn_add_term', 10, 3 );\n</code></pre>\n<p>Now, take the code in bravokeyls answer and instead of using <code>post_parent__not_in</code>, search for the tag in the hidden custom taxonomy:</p>\n<pre><code>/**\n * Only show attachments tagged as show_in_media_library\n **/\nfunction assets_hide_media( \\WP_Query $query ){\n if ( !is_admin() ) {\n return;\n }\n global $pagenow;\n if ( 'upload.php' != $pagenow && 'media-upload.php' != $pagenow ) {\n return;\n }\n\n if ( $query->is_main_query() ) {\n $query->set('hidden_taxonomy', 'show_in_media_library' );\n }\n\n return $query;\n}\nadd_action( 'pre_get_posts' , 'assets_hide_media' );\n</code></pre>\n<p>This should have a significant performance boost and scale better than using <code>post_parent__not_in</code>, and provides a taxonomy you can use to filter on other things</p>\n<p>This leaves you with one final problem. Attachments will only show if they have this term, but what about all the attachments you've already uploaded? We need to go back and add the term to those. To do this you would run a piece of code such as this once:</p>\n<pre><code>$q = new WP_Query( array(\n 'post_type' => 'attachment',\n 'post_status' => 'any',\n 'nopaging' => true,\n) );\n\nif ( $q->have_posts() ) {\n global $post;\n while ( $q->have_posts() ) {\n $q->the_post();\n\n $post_id = get_the_ID();\n\n $excluded_types = array( 'example_post_type', 'other_post_type' );\n if ( $post->post_parent ) {\n if ( in_array( get_post_type( $post->post_parent ), $excluded_types ) ) {\n echo "Skipping ".intval( $post_id )." ".esc_html( get_the_title() )."\\n";\n continue;\n }\n }\n echo "Setting term for ".intval( $post_id )." ".esc_html( get_the_title() )."\\n";\n $result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );\n if ( !is_array( $result ) || is_wp_error( $result ) ) {\n echo "Error setting up terms";\n }\n }\n wp_reset_postdata();\n} else {\n echo "No attachments found!\\n";\n}\n</code></pre>\n<p>I would recommend running this as a WP CLI command, especially if you have a lot of attachments that need processing</p>\n"
},
{
"answer_id": 289188,
"author": "EndyVelvet",
"author_id": 60574,
"author_profile": "https://wordpress.stackexchange.com/users/60574",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action( 'ajax_query_attachments_args' , 'custom_ajax_query_attachments_args' );\n\nfunction custom_ajax_query_attachments_args( $query ) {\n\n if( $query['post_type'] != 'attachment' ) {\n\n return $query;\n\n }\n\n\n $posts = get_posts([\n 'post_type' => 'YOUR_CUSTOM_POST_TYPE',\n 'post_status' => 'publish',\n 'numberposts' => -1\n ]);\n\n foreach($posts as $post){\n\n $excluded_cpt_ids[] = $post->ID;\n } \n\n $query['post_parent__not_in'] = $excluded_cpt_ids;\n\n return $query;\n\n}\n</code></pre>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84924/"
] |
We have created a CPT which allows our customer to upload files from the admin page to a folder outside of the wp-content/uploads folder. Files are uploaded and manipulated using wp\_handle\_upload and wp\_insert\_attachment.
How do we prevent these files from showing in the media library? Can we filter by post type?
Thanks in advance for any help!
**UPDATE:** here's the code we've implemented so far. New uploads are still not showing in the media library.
```
/*FORCE LIST VIEW IN MEDIA LIBRARY*/
add_action('admin_init', function() {
$_GET['mode'] = 'list';
}, 100);
/*HIDE GRID BUTTON IN MEDIA LIBRARY*/
add_action('admin_head', function() {
$css = '<style type="text/css">
.view-switch .view-grid {
display: none;
}
<style>';
echo $css;
});
/*REGISTER CUSTOM TAXONOMY*/
function create_hidden_taxonomy() {
register_taxonomy(
'hidden_taxonomy',
'attachment',
array(
'label' => __( 'Hidden Taxonomy' ),
'public' => false,
'rewrite' => false,
'hierarchical' => false,
)
);
}
add_action( 'init', 'create_hidden_taxonomy' );
/*CHECK IF PARENT POST TYPE IS ASSET. IF NOT ADD 'show_in_media_library' TERM*/
function assets_add_term( $post_id, \WP_Post $p, $update ) {
if ( 'attachment' !== $p->post_type ) {
error_log("fail1");
return;
}
if ( wp_is_post_revision( $post_id ) ) {
error_log("fail2");
return;
}
if ( $post->post_parent ) {
$excluded_types = array( 'assets' );
if ( in_array( get_post_type( $p->post_parent ), $excluded_types ) ) {
error_log("fail3");
return;
}
}
$result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );
if ( !is_array( $result ) || is_wp_error( $result ) ) {
error_log("fail4");
}else{
error_log("it worked!");
}
}
add_action( 'save_post', 'assets_add_term', 10, 2 );
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY*/
function assets_load_media() {
add_action('pre_get_posts','assets_hide_media',10,1);
}
add_action( 'load-upload.php' , 'assets_load_media' );
function assets_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = get_posts('post_type=assets&posts_per_page=-1&fields=ids');
$query->set('post_parent__not_in', $excluded_cpt_ids);
//$query->set('hidden_taxonomy', 'show_in_media_library' );
}
return $query;
}
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY MODAL*/
function assets_hide_media_modal( $query = array() ){
$query['post_parent__not_in'] = $excluded_cpt_ids;
return $query;
}
add_action('ajax_query_attachments_args','assets_hide_media_modal',10,1);
```
|
Media items are just like posts with **`post_type = attachment`** and **`post_status = inherit`**.
when we are on `upload.php` page, we have two views:
* List View
* Grid View
Grid view is populated via JavaScript and list view is extending normal **`WP_List_Table`**.
Since it (List view) is using normal post query we can use **`pre_get_posts`** to alter the query to hide required media items.
>
> How do we prevent these files from showing in the media library?
> Can
> we filter by post type?
>
>
>
We can't just filter the media items by `post_type` since media items post\_type is `attachment`. What you want is to filter media items by their **`post_parent's`** post ids.
```
add_action( 'load-upload.php' , 'wp_231165_load_media' );
function wp_231165_load_media() {
add_action('pre_get_posts','wp_231165_hide_media',10,1);
}
function wp_231165_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = array();//find a way to get all cpt post ids
$query->set('post_parent__not_in', $excluded_cpt_ids);
}
return $query;
}
```
Check [this question](https://wordpress.stackexchange.com/questions/165900/getting-the-ids-of-a-custom-post-type/165916) to get id's of a certain post type.
As @tomjnowell pointed out it works for list view but it's an expensive query.
One thing you can do is that add some meta value while uploading and query against that meta value
|
231,185 |
<p>I installed WordPress in my root directory <code>http://coinauctionshelp.com</code>. I want to redirect pages in the root to the new wordpress pages using an .htaccess file like this </p>
<p>301 redirect </p>
<pre><code>http://coinauctionshelp.com/United_States_Coin_Mintages_Price_Guides.html
http://coinauctionshelp.com/us-coin-values/
</code></pre>
<p>When I tried to do that I got a 500 internal server error so is there a quick fix for this?</p>
|
[
{
"answer_id": 231201,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 4,
"selected": true,
"text": "<p>Media items are just like posts with <strong><code>post_type = attachment</code></strong> and <strong><code>post_status = inherit</code></strong>.</p>\n\n<p>when we are on <code>upload.php</code> page, we have two views:</p>\n\n<ul>\n<li>List View</li>\n<li>Grid View</li>\n</ul>\n\n<p>Grid view is populated via JavaScript and list view is extending normal <strong><code>WP_List_Table</code></strong>.</p>\n\n<p>Since it (List view) is using normal post query we can use <strong><code>pre_get_posts</code></strong> to alter the query to hide required media items.</p>\n\n<blockquote>\n <p>How do we prevent these files from showing in the media library?<br />Can\n we filter by post type?</p>\n</blockquote>\n\n<p>We can't just filter the media items by <code>post_type</code> since media items post_type is <code>attachment</code>. What you want is to filter media items by their <strong><code>post_parent's</code></strong> post ids.</p>\n\n<pre><code>add_action( 'load-upload.php' , 'wp_231165_load_media' );\nfunction wp_231165_load_media() {\n add_action('pre_get_posts','wp_231165_hide_media',10,1);\n}\n\nfunction wp_231165_hide_media($query){\n global $pagenow;\n\n// there is no need to check for update.php as we are already hooking to it, but anyway\n if( 'upload.php' != $pagenow || !is_admin())\n return;\n\n if(is_main_query()){\n $excluded_cpt_ids = array();//find a way to get all cpt post ids\n $query->set('post_parent__not_in', $excluded_cpt_ids);\n }\n\n return $query;\n}\n</code></pre>\n\n<p>Check <a href=\"https://wordpress.stackexchange.com/questions/165900/getting-the-ids-of-a-custom-post-type/165916\">this question</a> to get id's of a certain post type.</p>\n\n<p>As @tomjnowell pointed out it works for list view but it's an expensive query.</p>\n\n<p>One thing you can do is that add some meta value while uploading and query against that meta value</p>\n"
},
{
"answer_id": 231210,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>When you create an attachment, do the following:</p>\n<ul>\n<li>If attachments parent ID is for a post with an excluded post type, do nothing</li>\n<li>If it isn't in the list of excluded post types, assign it a tag in a hidden custom taxonomy</li>\n</ul>\n<p>e.g.</p>\n<pre><code>function create_hidden_taxonomy() {\n register_taxonomy(\n 'hidden_taxonomy',\n 'attachment',\n array(\n 'label' => __( 'Hidden Attachment Taxonomy' ),\n 'public' => false, // it's hidden!\n 'rewrite' => false,\n 'hierarchical' => false,\n )\n );\n}\nadd_action( 'init', 'create_hidden_taxonomy' );\n\nfunction tomjn_add_term( $post_id, \\WP_Post $p, $update ) {\n\n if ( 'attachment' !== $p->post_type ) {\n return;\n }\n if ( wp_is_post_revision( $post_id ) ) {\n return;\n }\n if ( $p->post_parent ) {\n $excluded_types = array( 'example_post_type', 'other_post_type' );\n if ( in_array( get_post_type( $p->post_parent ), $excluded_types ) ) {\n return;\n }\n }\n $result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );\n if ( !is_array( $result ) || is_wp_error( $result ) ) {\n wp_die( "Error setting up terms") ;\n }\n}\nadd_action( 'save_post', 'tomjn_add_term', 10, 3 );\n</code></pre>\n<p>Now, take the code in bravokeyls answer and instead of using <code>post_parent__not_in</code>, search for the tag in the hidden custom taxonomy:</p>\n<pre><code>/**\n * Only show attachments tagged as show_in_media_library\n **/\nfunction assets_hide_media( \\WP_Query $query ){\n if ( !is_admin() ) {\n return;\n }\n global $pagenow;\n if ( 'upload.php' != $pagenow && 'media-upload.php' != $pagenow ) {\n return;\n }\n\n if ( $query->is_main_query() ) {\n $query->set('hidden_taxonomy', 'show_in_media_library' );\n }\n\n return $query;\n}\nadd_action( 'pre_get_posts' , 'assets_hide_media' );\n</code></pre>\n<p>This should have a significant performance boost and scale better than using <code>post_parent__not_in</code>, and provides a taxonomy you can use to filter on other things</p>\n<p>This leaves you with one final problem. Attachments will only show if they have this term, but what about all the attachments you've already uploaded? We need to go back and add the term to those. To do this you would run a piece of code such as this once:</p>\n<pre><code>$q = new WP_Query( array(\n 'post_type' => 'attachment',\n 'post_status' => 'any',\n 'nopaging' => true,\n) );\n\nif ( $q->have_posts() ) {\n global $post;\n while ( $q->have_posts() ) {\n $q->the_post();\n\n $post_id = get_the_ID();\n\n $excluded_types = array( 'example_post_type', 'other_post_type' );\n if ( $post->post_parent ) {\n if ( in_array( get_post_type( $post->post_parent ), $excluded_types ) ) {\n echo "Skipping ".intval( $post_id )." ".esc_html( get_the_title() )."\\n";\n continue;\n }\n }\n echo "Setting term for ".intval( $post_id )." ".esc_html( get_the_title() )."\\n";\n $result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );\n if ( !is_array( $result ) || is_wp_error( $result ) ) {\n echo "Error setting up terms";\n }\n }\n wp_reset_postdata();\n} else {\n echo "No attachments found!\\n";\n}\n</code></pre>\n<p>I would recommend running this as a WP CLI command, especially if you have a lot of attachments that need processing</p>\n"
},
{
"answer_id": 289188,
"author": "EndyVelvet",
"author_id": 60574,
"author_profile": "https://wordpress.stackexchange.com/users/60574",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action( 'ajax_query_attachments_args' , 'custom_ajax_query_attachments_args' );\n\nfunction custom_ajax_query_attachments_args( $query ) {\n\n if( $query['post_type'] != 'attachment' ) {\n\n return $query;\n\n }\n\n\n $posts = get_posts([\n 'post_type' => 'YOUR_CUSTOM_POST_TYPE',\n 'post_status' => 'publish',\n 'numberposts' => -1\n ]);\n\n foreach($posts as $post){\n\n $excluded_cpt_ids[] = $post->ID;\n } \n\n $query['post_parent__not_in'] = $excluded_cpt_ids;\n\n return $query;\n\n}\n</code></pre>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I installed WordPress in my root directory `http://coinauctionshelp.com`. I want to redirect pages in the root to the new wordpress pages using an .htaccess file like this
301 redirect
```
http://coinauctionshelp.com/United_States_Coin_Mintages_Price_Guides.html
http://coinauctionshelp.com/us-coin-values/
```
When I tried to do that I got a 500 internal server error so is there a quick fix for this?
|
Media items are just like posts with **`post_type = attachment`** and **`post_status = inherit`**.
when we are on `upload.php` page, we have two views:
* List View
* Grid View
Grid view is populated via JavaScript and list view is extending normal **`WP_List_Table`**.
Since it (List view) is using normal post query we can use **`pre_get_posts`** to alter the query to hide required media items.
>
> How do we prevent these files from showing in the media library?
> Can
> we filter by post type?
>
>
>
We can't just filter the media items by `post_type` since media items post\_type is `attachment`. What you want is to filter media items by their **`post_parent's`** post ids.
```
add_action( 'load-upload.php' , 'wp_231165_load_media' );
function wp_231165_load_media() {
add_action('pre_get_posts','wp_231165_hide_media',10,1);
}
function wp_231165_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = array();//find a way to get all cpt post ids
$query->set('post_parent__not_in', $excluded_cpt_ids);
}
return $query;
}
```
Check [this question](https://wordpress.stackexchange.com/questions/165900/getting-the-ids-of-a-custom-post-type/165916) to get id's of a certain post type.
As @tomjnowell pointed out it works for list view but it's an expensive query.
One thing you can do is that add some meta value while uploading and query against that meta value
|
231,212 |
<p>How to get term by custom term meta and taxonomy or how to filter <code>tax_query</code> by term meta instead <code>slug</code>/<code>id</code>?</p>
<pre><code>function custom_pre_get_posts($query)
{
global $wp_query;
if ( !is_admin() && is_shop() && $query->is_main_query() && is_post_type_archive( "product" ))
{
$term = ???get_term_by_meta_and_taxonomy???('custom_meta_term','my_taxonomy');
$t_id = $term['term_id'];
$tax_query = array
(
array
(
'taxonomy' => 'my_taxoomy',
'field' => 'id',
'terms' => $t_id
)
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
</code></pre>
|
[
{
"answer_id": 231242,
"author": "edwardr",
"author_id": 25724,
"author_profile": "https://wordpress.stackexchange.com/users/25724",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need to loop through each of the terms in your main query conditional. Assuming there will likely be more than one term with the custom data, you'll then need to pass an array of IDs into your tax query.</p>\n\n<p>For example, looping through each term to check for custom meta:</p>\n\n<pre><code>$term_args = array(\n 'taxonomy' => $taxonomy_name,\n );\n\n\n$terms = get_terms( $term_args );\n\n$term_ids = array();\n\nforeach( $terms as $term ) {\n $key = get_term_meta( $term->ID, 'meta_key', true );\n if( $key == 'meta_value' ) {\n // push the ID into the array\n $term_ids[] = $term->ID;\n }\n}\n</code></pre>\n\n<p>Then you end up with the variable $term_ids which contains an array of the term IDs you're looking for. You can pass that to your tax query.</p>\n"
},
{
"answer_id": 279102,
"author": "Ahmed Ali",
"author_id": 127242,
"author_profile": "https://wordpress.stackexchange.com/users/127242",
"pm_score": 4,
"selected": false,
"text": "<p>Try This:</p>\n\n<pre><code>$args = array(\n'hide_empty' => false, // also retrieve terms which are not used yet\n'meta_query' => array(\n array(\n 'key' => 'feature-group',\n 'value' => 'kitchen',\n 'compare' => 'LIKE'\n )\n),\n'taxonomy' => 'category',\n);\n$terms = get_terms( $args );\n</code></pre>\n"
},
{
"answer_id": 317716,
"author": "Steven Ryan",
"author_id": 69368,
"author_profile": "https://wordpress.stackexchange.com/users/69368",
"pm_score": 2,
"selected": false,
"text": "<p>Building on the answer from <a href=\"https://wordpress.stackexchange.com/users/126572/ilg%C4%B1t-y%C4%B1ld%C4%B1r%C4%B1m\">ilgıt-yıldırım</a> above, both the <code>get_term_meta</code> statement and <code>$key == 'meta_value'</code> statements need to contain <code>$term>term_id</code>.</p>\n\n<p>Here's a complete example including the custom <code>$wp_query</code> request:</p>\n\n<pre><code>$term_args = array( 'taxonomy' => 'your-taxonomy' );\n$terms = get_terms( $term_args );\n\n$term_ids = array();\n\nforeach( $terms as $term ) {\n $key = get_term_meta( $term->term_id, 'term-meta-key', true );\n\n if( $key == 'term-meta-value' ) {\n // push the ID into the array\n $term_ids[] = $term->term_id;\n }\n}\n\n// Loop Args\n$args = array(\n'post_type' => 'posts',\n'tax_query' => array(\n array(\n 'taxonomy' => 'your-taxonomy',\n 'terms' => $term_ids,\n ),\n ),\n);\n\n// The Query\n$featured = new WP_Query( $args );\n</code></pre>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97619/"
] |
How to get term by custom term meta and taxonomy or how to filter `tax_query` by term meta instead `slug`/`id`?
```
function custom_pre_get_posts($query)
{
global $wp_query;
if ( !is_admin() && is_shop() && $query->is_main_query() && is_post_type_archive( "product" ))
{
$term = ???get_term_by_meta_and_taxonomy???('custom_meta_term','my_taxonomy');
$t_id = $term['term_id'];
$tax_query = array
(
array
(
'taxonomy' => 'my_taxoomy',
'field' => 'id',
'terms' => $t_id
)
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
```
|
Try This:
```
$args = array(
'hide_empty' => false, // also retrieve terms which are not used yet
'meta_query' => array(
array(
'key' => 'feature-group',
'value' => 'kitchen',
'compare' => 'LIKE'
)
),
'taxonomy' => 'category',
);
$terms = get_terms( $args );
```
|
231,229 |
<p>I'm trying to determine if there's more than one page of comments in single.php. </p>
<p>In archive.php I can do something like this to check if there's more than one page of posts:</p>
<pre><code>if ( $wp_query->max_num_pages > 1 ) {
// There's more than one page of posts in this archive.
}
</code></pre>
<p>As far as I can tell, this doesn't work for comments. How can I check if comments are paginated in single.php?</p>
|
[
{
"answer_id": 231237,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>Try this, <code>get_option( 'page_comments' )</code> will check if pagination is checked in options > discussion, then we compare comments per page (<code>get_query_var( 'comments_per_page' )</code>) to the current post's total comments found (count):</p>\n\n<pre><code>function wpse231229_is_paginate_comments( $post_id = 0 ) {\n return get_option( 'page_comments' ) && ( $pagi = (int) get_query_var( 'comments_per_page' ) ) && wp_count_comments( $post_id )->total_comments > $pagi;\n}\n</code></pre>\n\n<p>Also, and to get the current page of comments (e.g <code>comment-page-1</code> in URL ..), use <code>(int) get_query_var( 'cpage' )</code></p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 231299,
"author": "henrywright",
"author_id": 22599,
"author_profile": "https://wordpress.stackexchange.com/users/22599",
"pm_score": 1,
"selected": false,
"text": "<p>One approach is to use the <code>cpage</code> query variable:</p>\n\n<pre><code>if ( ! empty( get_query_var( 'cpage' ) ) ) {\n // There is more than one page of comments.\n}\n</code></pre>\n"
},
{
"answer_id": 231315,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p><em>Just some additional info for the main comment query:</em></p>\n\n<p>Since you mentioned the global <code>$wp_query</code> object, we can see that it stores:</p>\n\n<pre><code>$wp_query->max_num_comment_pages = $comment_query->max_num_pages;\n</code></pre>\n\n<p>in the main comment query in the comments template.</p>\n\n<p>There <a href=\"https://codex.wordpress.org/Function_Reference/get_comment_pages_count\" rel=\"nofollow\">exists a wrapper</a> for this, namely:</p>\n\n<pre><code>get_comment_pages_count(); \n</code></pre>\n\n<p>that's available after the main comment query.</p>\n\n<p>If we need it before the main comment query runs, then we might check if\n<code>get_comments_number( $post_id )</code> is greater than <code>get_option( 'comments_per_page' )</code>. But we should keep in mind that the <code>comments_per_page</code> parameter can be modified through e.g. the <code>comments_template_query_args</code> filter.</p>\n"
}
] |
2016/07/01
|
[
"https://wordpress.stackexchange.com/questions/231229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22599/"
] |
I'm trying to determine if there's more than one page of comments in single.php.
In archive.php I can do something like this to check if there's more than one page of posts:
```
if ( $wp_query->max_num_pages > 1 ) {
// There's more than one page of posts in this archive.
}
```
As far as I can tell, this doesn't work for comments. How can I check if comments are paginated in single.php?
|
*Just some additional info for the main comment query:*
Since you mentioned the global `$wp_query` object, we can see that it stores:
```
$wp_query->max_num_comment_pages = $comment_query->max_num_pages;
```
in the main comment query in the comments template.
There [exists a wrapper](https://codex.wordpress.org/Function_Reference/get_comment_pages_count) for this, namely:
```
get_comment_pages_count();
```
that's available after the main comment query.
If we need it before the main comment query runs, then we might check if
`get_comments_number( $post_id )` is greater than `get_option( 'comments_per_page' )`. But we should keep in mind that the `comments_per_page` parameter can be modified through e.g. the `comments_template_query_args` filter.
|
231,251 |
<p>I have a typical shortcode which prints some html on a page. The shortcode will only be used on pages where visitors are logged in.</p>
<p>As a separate operation, I've been using a custom field to trigger an action which performs that test and then does the redirect.</p>
<p>But I was wondering if it was possible to combine that action into the shortcode and get rid of the custom field.</p>
<p>IOW: Can I make the shortcode print code in some tag in the header which tests to see if the visitor is logged in and if not, redirect them to the home page.</p>
<p>Eg.</p>
<pre><code>function jchForm() {
add_action( 'no idea where this would go', 'my_redirect_function' );
$s ='<div class="clearboth">';
$s .='<form id="my_form" action="" method="post">';
$s .='<p><label>Your Name</label><input id="user_name" type="text" name="user_name" class="text" value="" /></p>';
$s .='<p><label>Your Email Address</label><input id="user_email" type="text" name="user_email" class="text" value="" /></p>';
$s .='<p><input type="submit" id="my_submit" name="submit" value="Register" /></p>';
$s .='</form>';
$s .='</div>';
return $s;
</code></pre>
<p>}</p>
<p>UPDATE: I tried this, per the has_shortcode() function reference, but although it fires, $post always returns NULL. How do I get this to print -before- any other html but -after- the query grabs $post?</p>
<pre><code>function custom_shortcode_script() {
global $post;
if( is_user_logged_in() && has_shortcode( $post->post_content, 'jchForm') ) {
var_dump($post->post_content); // always prints NULL
wp_redirect( '/someplace');
}
}
add_action( 'init', 'custom_shortcode_script' );
</code></pre>
|
[
{
"answer_id": 231254,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 5,
"selected": true,
"text": "<p>Shortcode functions are only called when the content of the visual editor is processed and displayed, so nothing in your shortcode function will run early enough. </p>\n\n<p>Have a look at the <code>has_shortcode</code> function. If you hook in early enough to send headers and late enough for the query to be set up you can check if the content contains your shortcode and redirect then. The template_redirect hook is handy for this as it's about the last hook to be called before your theme sends output to the browser, which triggers PHP to send the headers. </p>\n"
},
{
"answer_id": 231267,
"author": "Caleb",
"author_id": 59678,
"author_profile": "https://wordpress.stackexchange.com/users/59678",
"pm_score": 1,
"selected": false,
"text": "<p>not a <code>wp_redirect()</code>, but you could do a JavaScript redirect:</p>\n\n<pre><code>window.location=\"http://www.example.com\";\n</code></pre>\n\n<p>won't do anything if the user has JS disabled, so make sure to provide a link for the redirect.</p>\n"
}
] |
2016/07/02
|
[
"https://wordpress.stackexchange.com/questions/231251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17248/"
] |
I have a typical shortcode which prints some html on a page. The shortcode will only be used on pages where visitors are logged in.
As a separate operation, I've been using a custom field to trigger an action which performs that test and then does the redirect.
But I was wondering if it was possible to combine that action into the shortcode and get rid of the custom field.
IOW: Can I make the shortcode print code in some tag in the header which tests to see if the visitor is logged in and if not, redirect them to the home page.
Eg.
```
function jchForm() {
add_action( 'no idea where this would go', 'my_redirect_function' );
$s ='<div class="clearboth">';
$s .='<form id="my_form" action="" method="post">';
$s .='<p><label>Your Name</label><input id="user_name" type="text" name="user_name" class="text" value="" /></p>';
$s .='<p><label>Your Email Address</label><input id="user_email" type="text" name="user_email" class="text" value="" /></p>';
$s .='<p><input type="submit" id="my_submit" name="submit" value="Register" /></p>';
$s .='</form>';
$s .='</div>';
return $s;
```
}
UPDATE: I tried this, per the has\_shortcode() function reference, but although it fires, $post always returns NULL. How do I get this to print -before- any other html but -after- the query grabs $post?
```
function custom_shortcode_script() {
global $post;
if( is_user_logged_in() && has_shortcode( $post->post_content, 'jchForm') ) {
var_dump($post->post_content); // always prints NULL
wp_redirect( '/someplace');
}
}
add_action( 'init', 'custom_shortcode_script' );
```
|
Shortcode functions are only called when the content of the visual editor is processed and displayed, so nothing in your shortcode function will run early enough.
Have a look at the `has_shortcode` function. If you hook in early enough to send headers and late enough for the query to be set up you can check if the content contains your shortcode and redirect then. The template\_redirect hook is handy for this as it's about the last hook to be called before your theme sends output to the browser, which triggers PHP to send the headers.
|
231,282 |
<p>I can't find if WordPress stores the number of items in a menu. Basically I need to find out how many items are in a menu to work out the percentage each item should take up in the header bar. Is there a function? Or is the best way to achieve this doing something with <code>WP_Query</code>?</p>
|
[
{
"answer_id": 231288,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>I was curious and decided to check it out, regardless if it's relevant for a CSS problem ;-)</p>\n\n<p>I first peeked into the database tables to find more about the menu structure:</p>\n\n<h2>Menu - building blocks</h2>\n\n<p>Each navigational menu is registered as a term in the <code>nav_menu</code> taxonomy.</p>\n\n<p>Then when we add items to that menu, we are creating new post objects of the type <code>nav_menu_item</code>.</p>\n\n<p>Now the tricky part, where's the tree structure for that menu stored?</p>\n\n<p>It's not the stored in the <code>post_parent</code> field of the <code>nav_menu_item</code> posts, as expected.</p>\n\n<p>We actually find it in the post meta table where it's stored under the <code>_menu_item_menu_item_parent</code> meta key, for each <code>nav_menu_item</code> post.</p>\n\n<p>Now there are various ways to get the count. Here are few examples:</p>\n\n<h2>Example - <code>get_term_by()</code> / <code>wp_get_nav_menu_object()</code></h2>\n\n<p>First the easy one: If we need to get the number of items in a particular menu we can actually get it from a term query, because it's stored in the <code>count</code> column of the <code>wp_term_taxonomy</code> table.</p>\n\n<p>First we get the menu term with:</p>\n\n<pre><code>$menuterm = get_term_by( 'slug', 'some-menu-slug', 'nav_menu' );\n</code></pre>\n\n<p>There's exists a wrapper for this, namely:</p>\n\n<pre><code>$menuterm = wp_get_nav_menu_object( 'some-menu-slug' );\n</code></pre>\n\n<p>To get the total count of items in the menu, we can then use:</p>\n\n<pre><code>$total_count = ( $menuterm instanceof \\WP_Term ) ? $menuterm->count : 0;\n</code></pre>\n\n<h2>Example - <code>WP_Query()</code> / <code>get_posts()</code></h2>\n\n<p>If we only want to count menu items without parents, then we can collect all the post objects within our menu with:</p>\n\n<pre><code>if( $menuterm instanceof \\WP_Term )\n $pids = get_objects_in_term( $menuterm->term_id, 'nav_menu' );\n</code></pre>\n\n<p>where <code>$pids</code> is an array of post IDs.</p>\n\n<p>Then we can make the following meta query:</p>\n\n<pre><code>$args = [\n 'post__in' => $pids,\n 'post_type' => 'nav_menu_item',\n 'fields' => 'ids',\n 'ignore_sticky_posts' => true,\n 'nopaging' => true,\n 'meta_query' => [\n [\n 'key' => '_menu_item_menu_item_parent',\n 'value' => 0,\n 'compare' => '=',\n ]\n ]\n]; \n\n$count = count( get_posts( $args ) );\n</code></pre>\n\n<p>There's also a way with:</p>\n\n<pre><code>$q = new WP_Query();\n$count = count( $q->query( $args ) );\n</code></pre>\n\n<p>or just:</p>\n\n<pre><code>$count = $q->found_posts;\n</code></pre>\n\n<p>with the common trick, <code>posts_per_page</code> as 1, to reduce fetched data.</p>\n\n<h2>Example - <code>wp_get_nav_menu_items()</code></h2>\n\n<p>There exists handy wrappers in core, like <code>wp_get_nav_menu_items( $menu, $args )</code> where <code>$args</code> are <code>get_posts()</code> arguments.</p>\n\n<p>Here's one way:</p>\n\n<pre><code>$count = count( \n wp_list_filter( \n wp_get_nav_menu_items( 'some-menu-slug' ), \n [ 'menu_item_parent' => 0 ] \n ) \n);\n</code></pre>\n\n<p>We can also use:</p>\n\n<pre><code>$args = [\n 'meta_query' => [\n [\n 'key' => '_menu_item_menu_item_parent',\n 'value' => 0,\n 'compare' => '=',\n ]\n ]\n];\n\n$count = count( wp_get_nav_menu_items( 'some-menu-slug', $args ) );\n</code></pre>\n\n<h2>Example - filter/hooks</h2>\n\n<p>There are many filters/actions that we could hook into to do the counting, e.g. the <code>wp_get_nav_menu_items</code> filter. Even hooks within the nav menu walker.</p>\n\n<p>We could even hook into the <code>wp_update_nav_menu</code> that fires when the menu is updated. Then we could count the items with no parents and store it e.g. as term meta data. </p>\n\n<p>Then there are also various ways with javascript.</p>\n\n<p>Hopefully this will give you some ideas to take this further.</p>\n"
},
{
"answer_id": 231515,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the help birgire. That gave me a lot to think about. Eventually I have came up with a solution using a filter I can count the number of parents the menu has. The only problem with this approach is that it will run every time a menu is displayed.</p>\n\n<pre><code>function my_nav_menu_objects($sorted_menu_items, $args) \n{\n if($args->menu == 'header_menu')\n {\n $counter = 0;\n\n foreach($sorted_menu_items as $sorted_menu_item)\n {\n if($sorted_menu_item->menu_item_parent == 0) \n {\n $counter++;\n }\n }\n\n echo 'Menu Count: ' . $counter;\n }\n\n return $sorted_menu_items;\n}\nadd_filter('wp_nav_menu_objects', 'my_nav_menu_objects', 10, 2);\n</code></pre>\n\n<p>Change the \"header_menu\" to what ever the slug of your navigation you want to check is. You could then store this into an option and call it when needed.</p>\n"
}
] |
2016/07/02
|
[
"https://wordpress.stackexchange.com/questions/231282",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75780/"
] |
I can't find if WordPress stores the number of items in a menu. Basically I need to find out how many items are in a menu to work out the percentage each item should take up in the header bar. Is there a function? Or is the best way to achieve this doing something with `WP_Query`?
|
I was curious and decided to check it out, regardless if it's relevant for a CSS problem ;-)
I first peeked into the database tables to find more about the menu structure:
Menu - building blocks
----------------------
Each navigational menu is registered as a term in the `nav_menu` taxonomy.
Then when we add items to that menu, we are creating new post objects of the type `nav_menu_item`.
Now the tricky part, where's the tree structure for that menu stored?
It's not the stored in the `post_parent` field of the `nav_menu_item` posts, as expected.
We actually find it in the post meta table where it's stored under the `_menu_item_menu_item_parent` meta key, for each `nav_menu_item` post.
Now there are various ways to get the count. Here are few examples:
Example - `get_term_by()` / `wp_get_nav_menu_object()`
------------------------------------------------------
First the easy one: If we need to get the number of items in a particular menu we can actually get it from a term query, because it's stored in the `count` column of the `wp_term_taxonomy` table.
First we get the menu term with:
```
$menuterm = get_term_by( 'slug', 'some-menu-slug', 'nav_menu' );
```
There's exists a wrapper for this, namely:
```
$menuterm = wp_get_nav_menu_object( 'some-menu-slug' );
```
To get the total count of items in the menu, we can then use:
```
$total_count = ( $menuterm instanceof \WP_Term ) ? $menuterm->count : 0;
```
Example - `WP_Query()` / `get_posts()`
--------------------------------------
If we only want to count menu items without parents, then we can collect all the post objects within our menu with:
```
if( $menuterm instanceof \WP_Term )
$pids = get_objects_in_term( $menuterm->term_id, 'nav_menu' );
```
where `$pids` is an array of post IDs.
Then we can make the following meta query:
```
$args = [
'post__in' => $pids,
'post_type' => 'nav_menu_item',
'fields' => 'ids',
'ignore_sticky_posts' => true,
'nopaging' => true,
'meta_query' => [
[
'key' => '_menu_item_menu_item_parent',
'value' => 0,
'compare' => '=',
]
]
];
$count = count( get_posts( $args ) );
```
There's also a way with:
```
$q = new WP_Query();
$count = count( $q->query( $args ) );
```
or just:
```
$count = $q->found_posts;
```
with the common trick, `posts_per_page` as 1, to reduce fetched data.
Example - `wp_get_nav_menu_items()`
-----------------------------------
There exists handy wrappers in core, like `wp_get_nav_menu_items( $menu, $args )` where `$args` are `get_posts()` arguments.
Here's one way:
```
$count = count(
wp_list_filter(
wp_get_nav_menu_items( 'some-menu-slug' ),
[ 'menu_item_parent' => 0 ]
)
);
```
We can also use:
```
$args = [
'meta_query' => [
[
'key' => '_menu_item_menu_item_parent',
'value' => 0,
'compare' => '=',
]
]
];
$count = count( wp_get_nav_menu_items( 'some-menu-slug', $args ) );
```
Example - filter/hooks
----------------------
There are many filters/actions that we could hook into to do the counting, e.g. the `wp_get_nav_menu_items` filter. Even hooks within the nav menu walker.
We could even hook into the `wp_update_nav_menu` that fires when the menu is updated. Then we could count the items with no parents and store it e.g. as term meta data.
Then there are also various ways with javascript.
Hopefully this will give you some ideas to take this further.
|
231,296 |
<p>A non-profit organisation (NPO) has a Wordpress website. The URL (example.com) carries the name of the NPO. The name of the NPO has changed so now we need to change the URL to reflect the new name. How do we do this, please?</p>
|
[
{
"answer_id": 231309,
"author": "ido barnea",
"author_id": 97755,
"author_profile": "https://wordpress.stackexchange.com/users/97755",
"pm_score": 0,
"selected": false,
"text": "<p>If you already own name 2 as a domain,\nBuild your web site on it, and when you are done you can redirect from old domain to the new one. That way you gain the power of the old domain too.</p>\n"
},
{
"answer_id": 231311,
"author": "Mdkusuma",
"author_id": 94687,
"author_profile": "https://wordpress.stackexchange.com/users/94687",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried editing your wp-config.php? If not, try to add or replace this value :</p>\n\n<pre><code>// DOMAIN & URL\n define('PROTOCOL', 'http://');\n define('DOMAIN_NAME', 'domain.tld');\n define('WP_SITEURL', PROTOCOL . DOMAIN_NAME);\n define('PATH_TO_WP', '/'); // if your WordPress is in a subdirectory.\n define('WP_HOME', WP_SITEURL . PATH_TO_WP); // root of your WordPress install \n</code></pre>\n\n<p>The <strong>wp-config.php</strong> is located in the <strong>root</strong> of your <strong>project directory</strong> by default. <a href=\"https://codex.wordpress.org/Editing_wp-config.php\" rel=\"nofollow\">Here</a> is the <strong>wordpress documentation</strong>. Hope that helps.</p>\n"
},
{
"answer_id": 231313,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 0,
"selected": false,
"text": "<p>While changing the Site URL under Settings -> General will change the website URL, it will also break the site.</p>\n\n<p>You should download the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and replace tool</a>, copy it on your webserver, run it and follow the on-screen instruction. The script will modify all the links in your db to reflect the domain change.</p>\n"
},
{
"answer_id": 231326,
"author": "Said El Bakkali",
"author_id": 78221,
"author_profile": "https://wordpress.stackexchange.com/users/78221",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way is to use <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">search and replace for wordpress databases</a></p>\n\n<p>Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.</p>\n\n<pre><code>RewriteEngine On\n\nRewriteCond %{HTTP_HOST} !^old-domain\\.com [NC]\n\nRewriteRule (.*) http://new-domain.com/$1 [R=301,L]\n</code></pre>\n\n<p>I hope I've helped you with my answer.</p>\n"
}
] |
2016/07/03
|
[
"https://wordpress.stackexchange.com/questions/231296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97744/"
] |
A non-profit organisation (NPO) has a Wordpress website. The URL (example.com) carries the name of the NPO. The name of the NPO has changed so now we need to change the URL to reflect the new name. How do we do this, please?
|
The easiest way is to use [search and replace for wordpress databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/)
Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^old-domain\.com [NC]
RewriteRule (.*) http://new-domain.com/$1 [R=301,L]
```
I hope I've helped you with my answer.
|
231,327 |
<p>How to configure .htaccess to this:
I need that my home page is <a href="http://mydomain.cl/c/news/" rel="nofollow">http://mydomain.cl/c/news/</a> but I cant do this.
Anyone want help me please?
Thanks!</p>
<p>Now, my htaccess is :</p>
<pre><code># 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>
</code></pre>
<h1>END WordPress</h1>
|
[
{
"answer_id": 231309,
"author": "ido barnea",
"author_id": 97755,
"author_profile": "https://wordpress.stackexchange.com/users/97755",
"pm_score": 0,
"selected": false,
"text": "<p>If you already own name 2 as a domain,\nBuild your web site on it, and when you are done you can redirect from old domain to the new one. That way you gain the power of the old domain too.</p>\n"
},
{
"answer_id": 231311,
"author": "Mdkusuma",
"author_id": 94687,
"author_profile": "https://wordpress.stackexchange.com/users/94687",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried editing your wp-config.php? If not, try to add or replace this value :</p>\n\n<pre><code>// DOMAIN & URL\n define('PROTOCOL', 'http://');\n define('DOMAIN_NAME', 'domain.tld');\n define('WP_SITEURL', PROTOCOL . DOMAIN_NAME);\n define('PATH_TO_WP', '/'); // if your WordPress is in a subdirectory.\n define('WP_HOME', WP_SITEURL . PATH_TO_WP); // root of your WordPress install \n</code></pre>\n\n<p>The <strong>wp-config.php</strong> is located in the <strong>root</strong> of your <strong>project directory</strong> by default. <a href=\"https://codex.wordpress.org/Editing_wp-config.php\" rel=\"nofollow\">Here</a> is the <strong>wordpress documentation</strong>. Hope that helps.</p>\n"
},
{
"answer_id": 231313,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 0,
"selected": false,
"text": "<p>While changing the Site URL under Settings -> General will change the website URL, it will also break the site.</p>\n\n<p>You should download the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and replace tool</a>, copy it on your webserver, run it and follow the on-screen instruction. The script will modify all the links in your db to reflect the domain change.</p>\n"
},
{
"answer_id": 231326,
"author": "Said El Bakkali",
"author_id": 78221,
"author_profile": "https://wordpress.stackexchange.com/users/78221",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way is to use <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">search and replace for wordpress databases</a></p>\n\n<p>Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.</p>\n\n<pre><code>RewriteEngine On\n\nRewriteCond %{HTTP_HOST} !^old-domain\\.com [NC]\n\nRewriteRule (.*) http://new-domain.com/$1 [R=301,L]\n</code></pre>\n\n<p>I hope I've helped you with my answer.</p>\n"
}
] |
2016/07/03
|
[
"https://wordpress.stackexchange.com/questions/231327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73011/"
] |
How to configure .htaccess to this:
I need that my home page is <http://mydomain.cl/c/news/> but I cant do this.
Anyone want help me please?
Thanks!
Now, my htaccess is :
```
# 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
=============
|
The easiest way is to use [search and replace for wordpress databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/)
Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^old-domain\.com [NC]
RewriteRule (.*) http://new-domain.com/$1 [R=301,L]
```
I hope I've helped you with my answer.
|
231,348 |
<p>I have a frustrating issue. I am using the <code>date_query</code> as referenced in the Codex: </p>
<pre><code><?php
$today = getdate();
$args = array(
'post_type' => 'Lighting',
'post_status' => 'publish',
'posts_per_page' => 1,
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$the_query = new WP_Query( $args );
</code></pre>
<p>While I can display custom posts as expected if I exclude <code>'day'</code>, I get no posts when it is included in the query. I am using <em>Advanced Custom Fields Pro</em> with the <code>date-picker</code>. I have no idea why this is happening, and I've searched tirelessly to determine why my <code>date_query</code> is not working. I am able to echo the date, so I don't understand where the disconnect is.</p>
<p>/****** RESPONSE TO ANSWERS ******/</p>
<p>Thanks for the responses. I have done a meta_query with what I think is the proper date format, but I am still unable to query only today's post. Here is the new query:</p>
<pre><code><?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event on today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-M-D"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'NUMERIC' // Let WordPress know we're working with numbers
)
)
);
</code></pre>
<p>Any suggestions? Thanks, again.</p>
<p>/******** SOLUTION **********/</p>
<p>Hi Everyone,</p>
<p>So, I found a solution that works. I changed the type to "DATE". It's interesting that in other examples where folks want to show todays date and beyond, they use a "Numeric" type. I guess it makes some sense, but I'm going to jump into the Codex to understand this more. I appreciate all of your help. Here is the solution that works:</p>
<pre><code> <?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event for today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'DATE' // Let WordPress know we're working with a date
)
)
);
</code></pre>
|
[
{
"answer_id": 231309,
"author": "ido barnea",
"author_id": 97755,
"author_profile": "https://wordpress.stackexchange.com/users/97755",
"pm_score": 0,
"selected": false,
"text": "<p>If you already own name 2 as a domain,\nBuild your web site on it, and when you are done you can redirect from old domain to the new one. That way you gain the power of the old domain too.</p>\n"
},
{
"answer_id": 231311,
"author": "Mdkusuma",
"author_id": 94687,
"author_profile": "https://wordpress.stackexchange.com/users/94687",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried editing your wp-config.php? If not, try to add or replace this value :</p>\n\n<pre><code>// DOMAIN & URL\n define('PROTOCOL', 'http://');\n define('DOMAIN_NAME', 'domain.tld');\n define('WP_SITEURL', PROTOCOL . DOMAIN_NAME);\n define('PATH_TO_WP', '/'); // if your WordPress is in a subdirectory.\n define('WP_HOME', WP_SITEURL . PATH_TO_WP); // root of your WordPress install \n</code></pre>\n\n<p>The <strong>wp-config.php</strong> is located in the <strong>root</strong> of your <strong>project directory</strong> by default. <a href=\"https://codex.wordpress.org/Editing_wp-config.php\" rel=\"nofollow\">Here</a> is the <strong>wordpress documentation</strong>. Hope that helps.</p>\n"
},
{
"answer_id": 231313,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 0,
"selected": false,
"text": "<p>While changing the Site URL under Settings -> General will change the website URL, it will also break the site.</p>\n\n<p>You should download the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and replace tool</a>, copy it on your webserver, run it and follow the on-screen instruction. The script will modify all the links in your db to reflect the domain change.</p>\n"
},
{
"answer_id": 231326,
"author": "Said El Bakkali",
"author_id": 78221,
"author_profile": "https://wordpress.stackexchange.com/users/78221",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way is to use <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">search and replace for wordpress databases</a></p>\n\n<p>Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.</p>\n\n<pre><code>RewriteEngine On\n\nRewriteCond %{HTTP_HOST} !^old-domain\\.com [NC]\n\nRewriteRule (.*) http://new-domain.com/$1 [R=301,L]\n</code></pre>\n\n<p>I hope I've helped you with my answer.</p>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231348",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97783/"
] |
I have a frustrating issue. I am using the `date_query` as referenced in the Codex:
```
<?php
$today = getdate();
$args = array(
'post_type' => 'Lighting',
'post_status' => 'publish',
'posts_per_page' => 1,
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$the_query = new WP_Query( $args );
```
While I can display custom posts as expected if I exclude `'day'`, I get no posts when it is included in the query. I am using *Advanced Custom Fields Pro* with the `date-picker`. I have no idea why this is happening, and I've searched tirelessly to determine why my `date_query` is not working. I am able to echo the date, so I don't understand where the disconnect is.
/\*\*\*\*\*\* RESPONSE TO ANSWERS \*\*\*\*\*\*/
Thanks for the responses. I have done a meta\_query with what I think is the proper date format, but I am still unable to query only today's post. Here is the new query:
```
<?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event on today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-M-D"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'NUMERIC' // Let WordPress know we're working with numbers
)
)
);
```
Any suggestions? Thanks, again.
/\*\*\*\*\*\*\*\* SOLUTION \*\*\*\*\*\*\*\*\*\*/
Hi Everyone,
So, I found a solution that works. I changed the type to "DATE". It's interesting that in other examples where folks want to show todays date and beyond, they use a "Numeric" type. I guess it makes some sense, but I'm going to jump into the Codex to understand this more. I appreciate all of your help. Here is the solution that works:
```
<?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event for today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'DATE' // Let WordPress know we're working with a date
)
)
);
```
|
The easiest way is to use [search and replace for wordpress databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/)
Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^old-domain\.com [NC]
RewriteRule (.*) http://new-domain.com/$1 [R=301,L]
```
I hope I've helped you with my answer.
|
231,361 |
<p>I am trying to create a custom post type. All are working fine except archive page. My custom post type archive page is archive-courses.php but is is not working it is showing default archive.php . Is there any wrong in my code? </p>
<p>Can anyone help me, please? </p>
<pre><code>function td_courses() {
$labels = array(
'name' => _x( 'Courses', 'td' ),
'singular_name' => _x( 'Courses', 'td' ),
'add_new' => _x( 'Add New', 'td' ),
'add_new_item' => __( 'Add New course' ),
'edit_item' => __( 'Edit course' ),
'new_item' => __( 'New courses' ),
'all_items' => __( 'Courses' ),
'view_item' => __( 'View courses' ),
'search_items' => __( 'Search courses' ),
'not_found' => __( 'No courses found' ),
'not_found_in_trash' => __( 'No courses found in the Trash' ),
'menu_name' => 'Courses'
);
$args = array(
'labels' => $labels,
'public' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-welcome-learn-more',
'supports' => array( 'title', 'editor', 'thumbnail', 'author' ),
'has_archive' => true,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'course' ),
);
register_post_type( 'courses', $args );
}
add_action( 'init', 'td_courses' );
function td_courses_taxonomies() {
$labels = array(
'name' => _x( 'Course Categories', 'td' ),
'singular_name' => _x( 'Course Categories', 'td' ),
'search_items' => __( 'Search Course Categorie' ),
'all_items' => __( 'All Course Categories' ),
'parent_item' => __( 'Parent Course Categorie' ),
'parent_item_colon' => __( 'Parent Course Categorie:' ),
'edit_item' => __( 'Edit Course Categorie' ),
'update_item' => __( 'Update Course Categorie' ),
'add_new_item' => __( 'Add New Course Categorie' ),
'new_item_name' => __( 'New Course Categorie Name' ),
'menu_name' => __( 'Course Categorie' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'courses-list' ),
);
register_taxonomy( 'courses_category', array( 'courses' ), $args );
}
add_action( 'init', 'td_courses_taxonomies', 0 );
</code></pre>
<p>Thanks </p>
|
[
{
"answer_id": 231365,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 3,
"selected": false,
"text": "<p>Your post type, <code>courses</code>, has a rewrite slug of <code>course</code>. So your archive template will be <code>archive-course.php</code>.</p>\n\n<p>Your taxonomy, <code>courses_category</code>, has a rewrite slug of <code>course</code>, so your taxonomy archive template will be <code>taxonomy-courses.php</code>.</p>\n\n<p>This complete <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview\" rel=\"noreferrer\">template hierarchy</a> can be useful.</p>\n\n<p>If you want an archive page showing <em>all</em> posts of the post type <code>courses</code> at <code>yoursite.com/courses</code>, you should assign the post type a rewrite slug of <code>courses</code>. (I believe this is the default since your post type is <code>courses</code>.)</p>\n\n<p>The taxonomy archive template, <code>taxonomy-[slug].php</code>, will be invoked when viewing an archive page of all posts of the post type <code>courses</code> assigned to a specific taxonomy term. So if you had a term <code>beginner</code>, and the rewrite slug <code>courses</code> for the taxonomy term, you'd see an archive of beginner courses at <code>yoursite.com/courses/beginner</code>.</p>\n\n<p>If you assign the same rewrite slug to the post type and the taxonomy, you may get some clashing. But I'm not sure.</p>\n\n<p>As Pieter Goosen said, you will need to flush the rewrite rules whenever you make changes like this.</p>\n"
},
{
"answer_id": 323196,
"author": "Felipe Volpato",
"author_id": 155744,
"author_profile": "https://wordpress.stackexchange.com/users/155744",
"pm_score": 2,
"selected": false,
"text": "<p>As Pieter Goosen said you need to flush your permalinks when creating a new taxonomy or custom post type. Go to your site settings -> permalinks and click on \"save button\".</p>\n\n<p>This did the trick for me.</p>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73498/"
] |
I am trying to create a custom post type. All are working fine except archive page. My custom post type archive page is archive-courses.php but is is not working it is showing default archive.php . Is there any wrong in my code?
Can anyone help me, please?
```
function td_courses() {
$labels = array(
'name' => _x( 'Courses', 'td' ),
'singular_name' => _x( 'Courses', 'td' ),
'add_new' => _x( 'Add New', 'td' ),
'add_new_item' => __( 'Add New course' ),
'edit_item' => __( 'Edit course' ),
'new_item' => __( 'New courses' ),
'all_items' => __( 'Courses' ),
'view_item' => __( 'View courses' ),
'search_items' => __( 'Search courses' ),
'not_found' => __( 'No courses found' ),
'not_found_in_trash' => __( 'No courses found in the Trash' ),
'menu_name' => 'Courses'
);
$args = array(
'labels' => $labels,
'public' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-welcome-learn-more',
'supports' => array( 'title', 'editor', 'thumbnail', 'author' ),
'has_archive' => true,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'course' ),
);
register_post_type( 'courses', $args );
}
add_action( 'init', 'td_courses' );
function td_courses_taxonomies() {
$labels = array(
'name' => _x( 'Course Categories', 'td' ),
'singular_name' => _x( 'Course Categories', 'td' ),
'search_items' => __( 'Search Course Categorie' ),
'all_items' => __( 'All Course Categories' ),
'parent_item' => __( 'Parent Course Categorie' ),
'parent_item_colon' => __( 'Parent Course Categorie:' ),
'edit_item' => __( 'Edit Course Categorie' ),
'update_item' => __( 'Update Course Categorie' ),
'add_new_item' => __( 'Add New Course Categorie' ),
'new_item_name' => __( 'New Course Categorie Name' ),
'menu_name' => __( 'Course Categorie' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'courses-list' ),
);
register_taxonomy( 'courses_category', array( 'courses' ), $args );
}
add_action( 'init', 'td_courses_taxonomies', 0 );
```
Thanks
|
Your post type, `courses`, has a rewrite slug of `course`. So your archive template will be `archive-course.php`.
Your taxonomy, `courses_category`, has a rewrite slug of `course`, so your taxonomy archive template will be `taxonomy-courses.php`.
This complete [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) can be useful.
If you want an archive page showing *all* posts of the post type `courses` at `yoursite.com/courses`, you should assign the post type a rewrite slug of `courses`. (I believe this is the default since your post type is `courses`.)
The taxonomy archive template, `taxonomy-[slug].php`, will be invoked when viewing an archive page of all posts of the post type `courses` assigned to a specific taxonomy term. So if you had a term `beginner`, and the rewrite slug `courses` for the taxonomy term, you'd see an archive of beginner courses at `yoursite.com/courses/beginner`.
If you assign the same rewrite slug to the post type and the taxonomy, you may get some clashing. But I'm not sure.
As Pieter Goosen said, you will need to flush the rewrite rules whenever you make changes like this.
|
231,362 |
<p>Here I mentioned the url</p>
<pre><code>http://localhost/wp/2016/?category_name=cricket
</code></pre>
<p>now i need to rearrange the url like </p>
<pre><code>http://localhost/wp/cricket/2016.
</code></pre>
<p>here cricket is category name and 2016 is year.</p>
<p>Remove the ?Query String Variable not a value of the querystring in the wordpress URl.</p>
<p>I tried </p>
<pre><code>RewriteRule ^([0-9]{4})/?$/(.+)/([^/]+)/?$ /index.php/$1/?category_name=$2[QSA,L]
</code></pre>
<p>But Not Working</p>
|
[
{
"answer_id": 231365,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 3,
"selected": false,
"text": "<p>Your post type, <code>courses</code>, has a rewrite slug of <code>course</code>. So your archive template will be <code>archive-course.php</code>.</p>\n\n<p>Your taxonomy, <code>courses_category</code>, has a rewrite slug of <code>course</code>, so your taxonomy archive template will be <code>taxonomy-courses.php</code>.</p>\n\n<p>This complete <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview\" rel=\"noreferrer\">template hierarchy</a> can be useful.</p>\n\n<p>If you want an archive page showing <em>all</em> posts of the post type <code>courses</code> at <code>yoursite.com/courses</code>, you should assign the post type a rewrite slug of <code>courses</code>. (I believe this is the default since your post type is <code>courses</code>.)</p>\n\n<p>The taxonomy archive template, <code>taxonomy-[slug].php</code>, will be invoked when viewing an archive page of all posts of the post type <code>courses</code> assigned to a specific taxonomy term. So if you had a term <code>beginner</code>, and the rewrite slug <code>courses</code> for the taxonomy term, you'd see an archive of beginner courses at <code>yoursite.com/courses/beginner</code>.</p>\n\n<p>If you assign the same rewrite slug to the post type and the taxonomy, you may get some clashing. But I'm not sure.</p>\n\n<p>As Pieter Goosen said, you will need to flush the rewrite rules whenever you make changes like this.</p>\n"
},
{
"answer_id": 323196,
"author": "Felipe Volpato",
"author_id": 155744,
"author_profile": "https://wordpress.stackexchange.com/users/155744",
"pm_score": 2,
"selected": false,
"text": "<p>As Pieter Goosen said you need to flush your permalinks when creating a new taxonomy or custom post type. Go to your site settings -> permalinks and click on \"save button\".</p>\n\n<p>This did the trick for me.</p>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97782/"
] |
Here I mentioned the url
```
http://localhost/wp/2016/?category_name=cricket
```
now i need to rearrange the url like
```
http://localhost/wp/cricket/2016.
```
here cricket is category name and 2016 is year.
Remove the ?Query String Variable not a value of the querystring in the wordpress URl.
I tried
```
RewriteRule ^([0-9]{4})/?$/(.+)/([^/]+)/?$ /index.php/$1/?category_name=$2[QSA,L]
```
But Not Working
|
Your post type, `courses`, has a rewrite slug of `course`. So your archive template will be `archive-course.php`.
Your taxonomy, `courses_category`, has a rewrite slug of `course`, so your taxonomy archive template will be `taxonomy-courses.php`.
This complete [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) can be useful.
If you want an archive page showing *all* posts of the post type `courses` at `yoursite.com/courses`, you should assign the post type a rewrite slug of `courses`. (I believe this is the default since your post type is `courses`.)
The taxonomy archive template, `taxonomy-[slug].php`, will be invoked when viewing an archive page of all posts of the post type `courses` assigned to a specific taxonomy term. So if you had a term `beginner`, and the rewrite slug `courses` for the taxonomy term, you'd see an archive of beginner courses at `yoursite.com/courses/beginner`.
If you assign the same rewrite slug to the post type and the taxonomy, you may get some clashing. But I'm not sure.
As Pieter Goosen said, you will need to flush the rewrite rules whenever you make changes like this.
|
231,374 |
<p>I need to get the comment author ID by the comment ID.</p>
<p><strong>Example</strong></p>
<pre><code>functionName($commentID){
return $authorID;
}
</code></pre>
|
[
{
"answer_id": 231399,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_comment\" rel=\"nofollow\"><code>get_comment</code></a> to return information about the comment like <code>comment_author_email</code>.</p>\n\n<p>You can then try to get a user by email using <a href=\"https://developer.wordpress.org/reference/functions/get_user_by/\" rel=\"nofollow\"><code>get_user_by</code>('email', $comment_author_email)</a>.</p>\n\n<p>Once you have the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow\"><code>WP_User</code></a> you should be able to access the <code>ID</code> of that user. </p>\n\n<p><em>All of this assumes, the comment author's email is used as the user's registration email.</em> </p>\n"
},
{
"answer_id": 302084,
"author": "l6ls",
"author_id": 141799,
"author_profile": "https://wordpress.stackexchange.com/users/141799",
"pm_score": 2,
"selected": false,
"text": "<p>you should use it: <code><?php get_comment( $id, $output ); ?></code></p>\n\n<h2>Return</h2>\n\n<pre><code>comment_ID \n(integer) The comment ID\ncomment_post_ID \n(integer) The post ID of the associated post\ncomment_author \n(string) The comment author's name\ncomment_author_email \n(string) The comment author's email\ncomment_author_url \n(string) The comment author's webpage\ncomment_author_IP \n(string) The comment author's IP\ncomment_date \n(string) The datetime of the comment (YYYY-MM-DD HH:MM:SS)\ncomment_date_gmt \n(string) The GMT datetime of the comment (YYYY-MM-DD HH:MM:SS)\ncomment_content \n(string) The comment's contents\ncomment_karma \n(integer) The comment's karma\ncomment_approved \n(string) The comment approbation (0, 1 or 'spam')\ncomment_agent \n(string) The comment's agent (browser, Operating System, etc.)\ncomment_type \n(string) The comment's type if meaningfull (pingback|trackback), and empty for normal comments\ncomment_parent \n(string) The parent comment's ID\nuser_id \n(integer) The comment author's ID if he is registered (0 otherwise)\n</code></pre>\n\n<h2>Final Code</h2>\n\n<pre><code>$comment_id = $commentID; //$commentID your var\n\n$comment = get_comment( $comment_id );\n\n$comment_author_id = $comment -> user_id;\n</code></pre>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97801/"
] |
I need to get the comment author ID by the comment ID.
**Example**
```
functionName($commentID){
return $authorID;
}
```
|
Use [`get_comment`](https://codex.wordpress.org/Function_Reference/get_comment) to return information about the comment like `comment_author_email`.
You can then try to get a user by email using [`get_user_by`('email', $comment\_author\_email)](https://developer.wordpress.org/reference/functions/get_user_by/).
Once you have the [`WP_User`](https://codex.wordpress.org/Class_Reference/WP_User) you should be able to access the `ID` of that user.
*All of this assumes, the comment author's email is used as the user's registration email.*
|
231,377 |
<p>Why file <code>plugins/woocommerce/assets/css/woocommerce.css</code>
for my template can not be read?</p>
<p>Please look this image :</p>
<p><a href="https://i.stack.imgur.com/1miMt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1miMt.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 231401,
"author": "Praveen",
"author_id": 97802,
"author_profile": "https://wordpress.stackexchange.com/users/97802",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function woocommmerce_style() {\n wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/woocommerce/assets/css/woocommerce.css',false,'1.0',\"all\");\n}\nadd_action( 'wp_head', 'woocommmerce_style' );\n</code></pre>\n\n<p>paste the above code in your \"functions.php\". woocommerce stylesheet will be executed to your site</p>\n"
},
{
"answer_id": 396140,
"author": "Ali H",
"author_id": 212896,
"author_profile": "https://wordpress.stackexchange.com/users/212896",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem, I added "woocommerce woocommerce-page" classes to body, or parents of woocommerce loop, so it solved the problem,</p>\n<p>actually, woocommerce main classes are not add to page.</p>\n"
},
{
"answer_id": 405170,
"author": "Leander",
"author_id": 21233,
"author_profile": "https://wordpress.stackexchange.com/users/21233",
"pm_score": 0,
"selected": false,
"text": "<p>As @ali-h correctly points out, the missing body classes are the culprit here...</p>\n<p>You can solve this by using the corresponding filter <code>body_class</code> and add your own classes, in this case the WooCommerce-specific ones:</p>\n<pre><code>/**\n * Add <body> classes\n */\nadd_filter('body_class', function (array $classes) {\n /** Add WC classes if on a custom template or when viewing search results */\n if (is_page_template('directory-name/page-something.php') || is_search()) {\n $classes[] = 'woocommerce woocommerce-page';\n }\n\n return array_filter($classes);\n});\n</code></pre>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97803/"
] |
Why file `plugins/woocommerce/assets/css/woocommerce.css`
for my template can not be read?
Please look this image :
[](https://i.stack.imgur.com/1miMt.png)
|
```
function woocommmerce_style() {
wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/woocommerce/assets/css/woocommerce.css',false,'1.0',"all");
}
add_action( 'wp_head', 'woocommmerce_style' );
```
paste the above code in your "functions.php". woocommerce stylesheet will be executed to your site
|
231,391 |
<p>I have a site which uses Google's API's for jquery and a fallback for jquery. The problem is that I can't get the fallback to happen immediately after the jquery api attempt. What happens is that the fallback file is added after a range of plugin scripts which require jquery and then fails. How can I change the order or location where these plugin scripts are added? Below just gives me the registered files:</p>
<pre><code>var_dump( $GLOBALS['wp_scripts']->registered );
</code></pre>
|
[
{
"answer_id": 231401,
"author": "Praveen",
"author_id": 97802,
"author_profile": "https://wordpress.stackexchange.com/users/97802",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function woocommmerce_style() {\n wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/woocommerce/assets/css/woocommerce.css',false,'1.0',\"all\");\n}\nadd_action( 'wp_head', 'woocommmerce_style' );\n</code></pre>\n\n<p>paste the above code in your \"functions.php\". woocommerce stylesheet will be executed to your site</p>\n"
},
{
"answer_id": 396140,
"author": "Ali H",
"author_id": 212896,
"author_profile": "https://wordpress.stackexchange.com/users/212896",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem, I added "woocommerce woocommerce-page" classes to body, or parents of woocommerce loop, so it solved the problem,</p>\n<p>actually, woocommerce main classes are not add to page.</p>\n"
},
{
"answer_id": 405170,
"author": "Leander",
"author_id": 21233,
"author_profile": "https://wordpress.stackexchange.com/users/21233",
"pm_score": 0,
"selected": false,
"text": "<p>As @ali-h correctly points out, the missing body classes are the culprit here...</p>\n<p>You can solve this by using the corresponding filter <code>body_class</code> and add your own classes, in this case the WooCommerce-specific ones:</p>\n<pre><code>/**\n * Add <body> classes\n */\nadd_filter('body_class', function (array $classes) {\n /** Add WC classes if on a custom template or when viewing search results */\n if (is_page_template('directory-name/page-something.php') || is_search()) {\n $classes[] = 'woocommerce woocommerce-page';\n }\n\n return array_filter($classes);\n});\n</code></pre>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94998/"
] |
I have a site which uses Google's API's for jquery and a fallback for jquery. The problem is that I can't get the fallback to happen immediately after the jquery api attempt. What happens is that the fallback file is added after a range of plugin scripts which require jquery and then fails. How can I change the order or location where these plugin scripts are added? Below just gives me the registered files:
```
var_dump( $GLOBALS['wp_scripts']->registered );
```
|
```
function woocommmerce_style() {
wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/woocommerce/assets/css/woocommerce.css',false,'1.0',"all");
}
add_action( 'wp_head', 'woocommmerce_style' );
```
paste the above code in your "functions.php". woocommerce stylesheet will be executed to your site
|
231,394 |
<p>I've got several search forms on my site and I want them to show different results. My website has a very strict hierarchy and the search form on a parent site should only show results from it's child pages.</p>
<p>My plan was to include different hidden fields on the different parent pages which contain the id of that particular page. In the <code>search.php</code> I then wanted to process the results and filter out the pages and posts that have no relation to the parent page.</p>
<p>Is there an easy way on how to achieve this?</p>
<p>Thanks in advance.</p>
<p><strong>EDIT 1</strong>
<hr>
This is my <code>search.php</code></p>
<pre><code><?php
if (have_posts()){
while(have_posts()){
the_post(); ?>
<div>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p><?php echo get_the_author(); ?> - <?php echo get_the_date(); ?></p>
<p><?php echo get_the_excerpt(); ?></p>
</div>
<?php
}
} else{ ?>
<h3>Sorry</h3>
<p>We are sorry but we could not find any matching articles on our site. Please try again with an other search request.</p>
<?php
get_search_form ();
}
?>
</code></pre>
<p>And the <code>searchform.php</code>:</p>
<pre><code><form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label>Search...</label>
<input type="text" name="s" id="s" value="<?php echo get_search_query(); ?>" placeholder="Search..." />
<input type="hidden" name="post_parent" value="<?php echo (int)get_the_ID(); ?>" />
<button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</form>
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>I also added <code><?php wp_reset_query(); ?></code> before the <code>if(have_posts()){}</code>. This results in no change. The pages are still shown.</p>
|
[
{
"answer_id": 231408,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>pre_get_posts</code> filter to filter out what you need. There's an example on how to do this in Codex:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_Pages_from_Search_Results\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_Pages_from_Search_Results</a></p>\n\n<pre><code>function search_filter($query) {\n if ( !is_admin() && $query->is_main_query() ) {\n if ($query->is_search) {\n $query->set('post_type', 'post');\n }\n }\n}\n\nadd_action('pre_get_posts','search_filter');\n</code></pre>\n\n<p>Also, <a href=\"http://www.billerickson.net/wordpress-search-post-type/\" rel=\"nofollow\">this</a> article might get you in the direction of editing the search form...</p>\n"
},
{
"answer_id": 231436,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>While the <code>pre_get_posts</code> filter is going to let you modify the main query before it happens, letting you add extra requirements, in this case it isn't necessary! You can do it all with the URL and the search form</p>\n\n<p>First, the query variables passed into <code>WP_Query</code> can be used in the URL. <code>post_parent</code> being the query var you're wanting.</p>\n\n<p>So if we have this:</p>\n\n<pre><code><form action=\"/\" method=\"get\">\n <input type=\"text\" name=\"s\" />\n <input type=\"hidden\" name=\"post_parent\" value=\"<?php echo (int)get_the_ID(); ?>\"/>\n <input type=\"hidden\" name=\"post_type\" value=\"page\"/>\n</form>\n</code></pre>\n\n<p>Then any search results will be limited to those whose post_parent is the page that the search came from. You'll see URLs such as <code>/?s=test&post_parent=123</code>.</p>\n\n<p>This trick can be used to filter by categories and authors, for example, searching a category:</p>\n\n<p><code>/category/example/?s=test</code></p>\n\n<p>Only showing posts by a particular author in a date archive:</p>\n\n<p><code>/2016/?author=123</code></p>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93282/"
] |
I've got several search forms on my site and I want them to show different results. My website has a very strict hierarchy and the search form on a parent site should only show results from it's child pages.
My plan was to include different hidden fields on the different parent pages which contain the id of that particular page. In the `search.php` I then wanted to process the results and filter out the pages and posts that have no relation to the parent page.
Is there an easy way on how to achieve this?
Thanks in advance.
**EDIT 1**
---
This is my `search.php`
```
<?php
if (have_posts()){
while(have_posts()){
the_post(); ?>
<div>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p><?php echo get_the_author(); ?> - <?php echo get_the_date(); ?></p>
<p><?php echo get_the_excerpt(); ?></p>
</div>
<?php
}
} else{ ?>
<h3>Sorry</h3>
<p>We are sorry but we could not find any matching articles on our site. Please try again with an other search request.</p>
<?php
get_search_form ();
}
?>
```
And the `searchform.php`:
```
<form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label>Search...</label>
<input type="text" name="s" id="s" value="<?php echo get_search_query(); ?>" placeholder="Search..." />
<input type="hidden" name="post_parent" value="<?php echo (int)get_the_ID(); ?>" />
<button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</form>
```
**EDIT 2**
I also added `<?php wp_reset_query(); ?>` before the `if(have_posts()){}`. This results in no change. The pages are still shown.
|
You can use `pre_get_posts` filter to filter out what you need. There's an example on how to do this in Codex:
<https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_Pages_from_Search_Results>
```
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
add_action('pre_get_posts','search_filter');
```
Also, [this](http://www.billerickson.net/wordpress-search-post-type/) article might get you in the direction of editing the search form...
|
231,407 |
<p>I am using the <a href="https://wordpress.org/plugins/wp-job-manager/" rel="nofollow">wp-job-manager plugin</a> and i want to add an Adsense code between the job listings ( after fifth job listing ) in the page with [jobs] shortcode.</p>
<p>The function that outputs the jobs resides in <a href="https://github.com/Automattic/WP-Job-Manager/blob/master/includes/class-wp-job-manager-shortcodes.php" rel="nofollow"><code>class-wp-job-manager-shortcodes.php</code></a> <strong>function <code>output_jobs( $atts )</code></strong></p>
<p>Because i don't know how to start to add that Adsense code to this function using action hooks or what else i need some help to make it work.</p>
|
[
{
"answer_id": 231409,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 1,
"selected": false,
"text": "<p>There's a filter for the output</p>\n\n<pre><code> $job_listings_output = apply_filters( 'job_manager_job_listings_output', ob_get_clean() );\n</code></pre>\n\n<p>so, you should just do</p>\n\n<pre><code>add_filter('job_manager_job_listings_output','my_job_manager_job_listings_output');\nfunction my_job_manager_job_listings_output($output) {\n $adsense_code = ' My adsense code';\n return $output . $adsence_code;\n}\n</code></pre>\n"
},
{
"answer_id": 408298,
"author": "andyrandy",
"author_id": 181145,
"author_profile": "https://wordpress.stackexchange.com/users/181145",
"pm_score": 0,
"selected": false,
"text": "<p>I just had the same problem, afaik you cannot get "every nth occurance", so i just used explode/implode. I had to do it twice, because my jobs get loaded by ajax too and there is another filter for that:</p>\n<pre><code>add_filter('job_manager_job_listings_output', function ($output) {\n $adsense_code = 'xxx';\n $temp_result_exploded = explode('</li>', $output);\n $temp_result = [];\n for ($i = 0; $i < count($temp_result_exploded); $i++) {\n $temp_result[] = $temp_result_exploded[$i];\n if ($i % 5 === 0 && $i > 0) {\n $temp_result[] = '<li>' . $adsense_code;\n }\n }\n return implode('</li>', $temp_result);\n});\n\nadd_filter('job_manager_get_listings_result', function($result, $jobs) {\n $adsense_code = 'xxx';\n $temp_result_exploded = explode('</li>', $result['html']);\n $temp_result = [];\n for ($i = 0; $i < count($temp_result_exploded); $i++) {\n $temp_result[] = $temp_result_exploded[$i];\n if ($i % 5 === 0 && $i > 0) {\n $temp_result[] = '<li>' . $adsense_code;\n }\n }\n $result['html'] = implode('</li>', $temp_result);\n return $result;\n}, 10, 2);\n</code></pre>\n<p>Of course there is some redundant code, but this is just an example :)</p>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231407",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96329/"
] |
I am using the [wp-job-manager plugin](https://wordpress.org/plugins/wp-job-manager/) and i want to add an Adsense code between the job listings ( after fifth job listing ) in the page with [jobs] shortcode.
The function that outputs the jobs resides in [`class-wp-job-manager-shortcodes.php`](https://github.com/Automattic/WP-Job-Manager/blob/master/includes/class-wp-job-manager-shortcodes.php) **function `output_jobs( $atts )`**
Because i don't know how to start to add that Adsense code to this function using action hooks or what else i need some help to make it work.
|
There's a filter for the output
```
$job_listings_output = apply_filters( 'job_manager_job_listings_output', ob_get_clean() );
```
so, you should just do
```
add_filter('job_manager_job_listings_output','my_job_manager_job_listings_output');
function my_job_manager_job_listings_output($output) {
$adsense_code = ' My adsense code';
return $output . $adsence_code;
}
```
|
231,415 |
<p>I have a contact form in a WordPress page like this:</p>
<pre><code>$( '#contact_form' ).bootstrapValidator({
fields: {
// ...
},
submitHandler: function( formInstance ) {
$.post( "../send-message", $("#contact_form").serialize(), function( result ) {
alert( pw_script_vars.State );
});
}
});
</code></pre>
<p>When the form is submitted using the Ajax request it goes to another WordPress page titled <code>/send-message</code> that has PHP code to send an email, then it should return a success or failure value to the Ajax request to alert a success or failure message. I have tried using the <code>wp_localize_script</code> function in the <code>functions.php</code> file using a fixed value and it worked fine:</p>
<pre><code>function enqueue_scripts() {
wp_enqueue_script( 'pw_script', get_stylesheet_directory_uri().'/inc/js/functions.min.js', array( 'jquery' ) );
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
</code></pre>
<p>But when I tried to use the <code>wp_localize_script</code> in the <code>/send-message</code> WordPress page it failed to work. Here are the contents of the '/send-message' page :</p>
<pre><code><?php
$sendSuccess = sendMessage();
if( $sendSuccess )
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
else
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'failure' ) );
function sendMessage() {
//This function will send the email then it will return true or false.
}
?>
</code></pre>
<p>Using <code>wp_localize_script</code> in the <code>/send-message</code> causes an undefined variable <code>pw_script_vars</code> in the JavaScript file.</p>
<p>How can I use <code>wp_localize_script</code> in a WordPress page other than <code>functions.php</code>?</p>
|
[
{
"answer_id": 231418,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot use <code>wp_localize_script</code> in page template. You have to use it in <code>functions.php</code> or your custom plugin, after you register your script, which is usually in the <code>wp_enqueue_scripts</code> action.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_localize_script</a></p>\n"
},
{
"answer_id": 231502,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need to move your wp_localize_script anywhere else. Your problem lies within the fact that you try to use AJAX outside of WordPress. Let me refer to an earlier answer of me showing a simple version of how to use AJAX in WordPress <a href=\"https://wordpress.stackexchange.com/a/229576/81939\">here</a></p>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231415",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97480/"
] |
I have a contact form in a WordPress page like this:
```
$( '#contact_form' ).bootstrapValidator({
fields: {
// ...
},
submitHandler: function( formInstance ) {
$.post( "../send-message", $("#contact_form").serialize(), function( result ) {
alert( pw_script_vars.State );
});
}
});
```
When the form is submitted using the Ajax request it goes to another WordPress page titled `/send-message` that has PHP code to send an email, then it should return a success or failure value to the Ajax request to alert a success or failure message. I have tried using the `wp_localize_script` function in the `functions.php` file using a fixed value and it worked fine:
```
function enqueue_scripts() {
wp_enqueue_script( 'pw_script', get_stylesheet_directory_uri().'/inc/js/functions.min.js', array( 'jquery' ) );
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
```
But when I tried to use the `wp_localize_script` in the `/send-message` WordPress page it failed to work. Here are the contents of the '/send-message' page :
```
<?php
$sendSuccess = sendMessage();
if( $sendSuccess )
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
else
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'failure' ) );
function sendMessage() {
//This function will send the email then it will return true or false.
}
?>
```
Using `wp_localize_script` in the `/send-message` causes an undefined variable `pw_script_vars` in the JavaScript file.
How can I use `wp_localize_script` in a WordPress page other than `functions.php`?
|
You cannot use `wp_localize_script` in page template. You have to use it in `functions.php` or your custom plugin, after you register your script, which is usually in the `wp_enqueue_scripts` action.
<https://codex.wordpress.org/Function_Reference/wp_localize_script>
|
231,424 |
<p>If I'm just echoing regular text, I do this:</p>
<pre><code><?php _e('This post is closed to new comments.','my-theme') ?>
</code></pre>
<p>But how would I translate the text in <code>comments_number();</code> so that the "Comments" text can be translated? Like this:</p>
<pre><code><?php comments_number( 'Comments (0)', 'Comments (1)', 'Comments (%)' ); ?>
</code></pre>
|
[
{
"answer_id": 231426,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": -1,
"selected": false,
"text": "<p>The <code>comments_number</code> function is calling <code>get_comments_number_text</code> function: <a href=\"https://developer.wordpress.org/reference/functions/get_comments_number_text/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/get_comments_number_text/</a></p>\n\n<p>In that function there are your strings to translate</p>\n\n<pre><code>function get_comments_number_text( $zero = false, $one = false, $more = false ) {\n $number = get_comments_number();\n\n if ( $number > 1 ) {\n if ( false === $more ) {\n /* translators: %s: number of comments */\n $output = sprintf( _n( '%s Comment', '%s Comments', $number ), number_format_i18n( $number ) );\n } else {\n // % Comments\n $output = str_replace( '%', number_format_i18n( $number ), $more );\n }\n } elseif ( $number == 0 ) {\n $output = ( false === $zero ) ? __( 'No Comments' ) : $zero;\n } else { // must be one\n $output = ( false === $one ) ? __( '1 Comment' ) : $one;\n }\n /**\n * Filter the comments count for display.\n *\n * @since 1.5.0\n *\n * @see _n()\n *\n * @param string $output A translatable string formatted based on whether the count\n * is equal to 0, 1, or 1+.\n * @param int $number The number of post comments.\n */\n return apply_filters( 'comments_number', $output, $number );\n}\n</code></pre>\n"
},
{
"answer_id": 231707,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You have to make these strings translatable by using <code>__()</code> function:</p>\n\n<pre><code>comments_number( __('Comments (0)'), __('Comments (1)'), __('Comments (%)') );\n</code></pre>\n\n<p>If you want to use the custom <code>textdomain</code>, e.g. <code>'test'</code>:</p>\n\n<pre><code>comments_number( __('Comments (0)', 'test'), __('Comments (1)', 'test'), __('Comments (%)', 'test') );\n</code></pre>\n\n<p>For more information see:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/_2\" rel=\"nofollow\">__()</a></li>\n<li><a href=\"https://developer.wordpress.org/themes/functionality/internationalization/\" rel=\"nofollow\">Theme internationalization</a></li>\n<li>Very good article by Samuel Wood a.k.a. Otto: <a href=\"http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/\" rel=\"nofollow\">Internationalization: You’re probably doing it wrong</a>.</li>\n</ul>\n"
}
] |
2016/07/04
|
[
"https://wordpress.stackexchange.com/questions/231424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91783/"
] |
If I'm just echoing regular text, I do this:
```
<?php _e('This post is closed to new comments.','my-theme') ?>
```
But how would I translate the text in `comments_number();` so that the "Comments" text can be translated? Like this:
```
<?php comments_number( 'Comments (0)', 'Comments (1)', 'Comments (%)' ); ?>
```
|
You have to make these strings translatable by using `__()` function:
```
comments_number( __('Comments (0)'), __('Comments (1)'), __('Comments (%)') );
```
If you want to use the custom `textdomain`, e.g. `'test'`:
```
comments_number( __('Comments (0)', 'test'), __('Comments (1)', 'test'), __('Comments (%)', 'test') );
```
For more information see:
* [\_\_()](https://codex.wordpress.org/Function_Reference/_2)
* [Theme internationalization](https://developer.wordpress.org/themes/functionality/internationalization/)
* Very good article by Samuel Wood a.k.a. Otto: [Internationalization: You’re probably doing it wrong](http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/).
|
231,448 |
<p>How to add dot(<code>.</code>) in post slugs?</p>
<p>In our blog, we are writing about websites and would like to use their exact address as slug like this:</p>
<p><code>ourdomain.com/<strong>example1.com</strong></code></p>
<p>But dots are either removed when a post is saved, or WordPress doesn't find the post when we successfully add one.</p>
<p>Is there any option available?</p>
|
[
{
"answer_id": 231952,
"author": "Andy",
"author_id": 43719,
"author_profile": "https://wordpress.stackexchange.com/users/43719",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress runs slugs through its <code>sanitize_title_with_dashes()</code> filter function which replaces dots with dashes. Unfortunately the function doesn't give you any control over that or any ability to change what characters are stripped or replaced.</p>\n\n<p>What we can do however is remove that filter and add our own version of it with a couple of modifications:</p>\n\n<pre><code>remove_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10 );\nadd_filter( 'sanitize_title', 'wpse231448_sanitize_title_with_dashes', 10, 3 );\n\nfunction wpse231448_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {\n $title = strip_tags($title);\n // Preserve escaped octets.\n $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);\n // Remove percent signs that are not part of an octet.\n $title = str_replace('%', '', $title);\n // Restore octets.\n $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);\n\n if (seems_utf8($title)) {\n if (function_exists('mb_strtolower')) {\n $title = mb_strtolower($title, 'UTF-8');\n }\n $title = utf8_uri_encode($title, 200);\n }\n\n $title = strtolower($title);\n\n if ( 'save' == $context ) {\n // Convert nbsp, ndash and mdash to hyphens\n $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );\n // Convert nbsp, ndash and mdash HTML entities to hyphens\n $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', $title );\n\n // Strip these characters entirely\n $title = str_replace( array(\n // iexcl and iquest\n '%c2%a1', '%c2%bf',\n // angle quotes\n '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',\n // curly quotes\n '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',\n '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',\n // copy, reg, deg, hellip and trade\n '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',\n // acute accents\n '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',\n // grave accent, macron, caron\n '%cc%80', '%cc%84', '%cc%8c',\n ), '', $title );\n\n // Convert times to x\n $title = str_replace( '%c3%97', 'x', $title );\n }\n\n $title = preg_replace('/&.+?;/', '', $title); // kill entities\n\n // WPSE-231448: Commented out this line below to stop dots being replaced by dashes.\n //$title = str_replace('.', '-', $title);\n\n // WPSE-231448: Add the dot to the list of characters NOT to be stripped.\n $title = preg_replace('/[^%a-z0-9 _\\-\\.]/', '', $title);\n $title = preg_replace('/\\s+/', '-', $title);\n $title = preg_replace('|-+|', '-', $title);\n $title = trim($title, '-');\n\n return $title;\n}\n</code></pre>\n\n<p>The lines I edited are commented with a \"WPSE-231448\" - First I commented out the line which does a <code>str_replace()</code> and replaces dots with dashes, then I added the dot to the list of characters to NOT be replaced in the <code>preg_replace()</code> function below that.</p>\n\n<p>Please note that I have not tested this with pagination or anything like that, it simply stops dots being stripped from slugs on the front/backend and any issues that may arise from that will need to be handled accordingly.</p>\n"
},
{
"answer_id": 360360,
"author": "suresh",
"author_id": 29327,
"author_profile": "https://wordpress.stackexchange.com/users/29327",
"pm_score": 1,
"selected": false,
"text": "<p><strong>PLUGIN:</strong> we can use the following plugin <a href=\"https://wordpress.org/plugins/permalink-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/permalink-manager/</a> \nthis plugins helped me if you want to edit some of the posts.</p>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48647/"
] |
How to add dot(`.`) in post slugs?
In our blog, we are writing about websites and would like to use their exact address as slug like this:
`ourdomain.com/**example1.com**`
But dots are either removed when a post is saved, or WordPress doesn't find the post when we successfully add one.
Is there any option available?
|
WordPress runs slugs through its `sanitize_title_with_dashes()` filter function which replaces dots with dashes. Unfortunately the function doesn't give you any control over that or any ability to change what characters are stripped or replaced.
What we can do however is remove that filter and add our own version of it with a couple of modifications:
```
remove_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10 );
add_filter( 'sanitize_title', 'wpse231448_sanitize_title_with_dashes', 10, 3 );
function wpse231448_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Convert nbsp, ndash and mdash HTML entities to hyphens
$title = str_replace( array( ' ', ' ', '–', '–', '—', '—' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// acute accents
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
// grave accent, macron, caron
'%cc%80', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/&.+?;/', '', $title); // kill entities
// WPSE-231448: Commented out this line below to stop dots being replaced by dashes.
//$title = str_replace('.', '-', $title);
// WPSE-231448: Add the dot to the list of characters NOT to be stripped.
$title = preg_replace('/[^%a-z0-9 _\-\.]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
```
The lines I edited are commented with a "WPSE-231448" - First I commented out the line which does a `str_replace()` and replaces dots with dashes, then I added the dot to the list of characters to NOT be replaced in the `preg_replace()` function below that.
Please note that I have not tested this with pagination or anything like that, it simply stops dots being stripped from slugs on the front/backend and any issues that may arise from that will need to be handled accordingly.
|
231,469 |
<p>I basically need to change the date format to german date format all over the WordPress site and I succeed it by changing the date time settings from the WordPress admin panel.</p>
<blockquote>
<p><strong>Settings » General</strong> :</p>
<p><strong>Date Format</strong> - Custom : j. F Y</p>
<p>eg : 5. July 2016</p>
</blockquote>
<p>However I need to change the month names to german as well.</p>
<blockquote>
<p>eg : 5. Juli 2016</p>
</blockquote>
<p>How should I do that ?</p>
|
[
{
"answer_id": 231472,
"author": "Aipo",
"author_id": 67135,
"author_profile": "https://wordpress.stackexchange.com/users/67135",
"pm_score": 1,
"selected": false,
"text": "<p>Use locale in <code>wp-config.php</code> de_DE, language settings depends on admin panel language, it is possible to separate site language and admin panel language. \nAlso in wp-content>languages look for <code>de_DE.po</code>, use search.</p>\n"
},
{
"answer_id": 231480,
"author": "Janith Chinthana",
"author_id": 68403,
"author_profile": "https://wordpress.stackexchange.com/users/68403",
"pm_score": 3,
"selected": true,
"text": "<p>I have added the following code to child theme function and it works,</p>\n\n<pre><code>add_filter('the_time', 'modify_date_format');\nfunction modify_date_format(){\n $month_names = array(1=>'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');\n return get_the_time('j').'. '.$month_names[get_the_time('n')].' '.get_the_time('Y');\n}\n</code></pre>\n\n<p>But I'm not sure this is the correct way to do it.</p>\n"
},
{
"answer_id": 231498,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress has a special function for translating dates, called <a href=\"https://codex.wordpress.org/Function_Reference/date_i18n\" rel=\"noreferrer\"><code>date_i18n</code></a>. General usage:</p>\n\n<pre><code>echo date_i18n( $dateformatstring, $unixtimestamp, $gmt);\n</code></pre>\n\n<p>Supposing you have German as your site's language this would be:</p>\n\n<pre><code>echo date_i18n( 'j. F Y', false, false);\n</code></pre>\n\n<p>You can also import the time format from the admin settings, like this:</p>\n\n<pre><code>echo date_i18n(get_option('date_format'), false, false);\n</code></pre>\n"
},
{
"answer_id": 231506,
"author": "Ramcharan",
"author_id": 93914,
"author_profile": "https://wordpress.stackexchange.com/users/93914",
"pm_score": 2,
"selected": false,
"text": "<p>go to admin follow 2 simple steps </p>\n\n<ol>\n<li><p>Date Format - Custom : j. F Y</p></li>\n<li><p>Change Site Language which one you want change and then save </p></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/IznAo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IznAo.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231469",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68403/"
] |
I basically need to change the date format to german date format all over the WordPress site and I succeed it by changing the date time settings from the WordPress admin panel.
>
> **Settings » General** :
>
>
> **Date Format** - Custom : j. F Y
>
>
> eg : 5. July 2016
>
>
>
However I need to change the month names to german as well.
>
> eg : 5. Juli 2016
>
>
>
How should I do that ?
|
I have added the following code to child theme function and it works,
```
add_filter('the_time', 'modify_date_format');
function modify_date_format(){
$month_names = array(1=>'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');
return get_the_time('j').'. '.$month_names[get_the_time('n')].' '.get_the_time('Y');
}
```
But I'm not sure this is the correct way to do it.
|
231,479 |
<p>I've inherited a very poorly designed WordPress site that in part uses BuddyPress for a directory type section. Users are able to upload profile images and 'product' images to their profile.</p>
<p>As a result, we now have roughly 20GB of images on the site and desperately need to cut back on this. When users, stop paying a membership fee to the charity running the site, the users role is changed from one of several custom roles back to the WP 'Subscriber' role.</p>
<p>My hope is that there is a fairly simple and accurate way to find images associated with a user or users profile and then delete these images if the users is has the 'Subscriber' role.</p>
<p>At present I've not tried anything along these lines, and am hoping someone with more WP dev experience might be able to give me some tips / suggestions on how to approach this.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 231499,
"author": "Conor",
"author_id": 47324,
"author_profile": "https://wordpress.stackexchange.com/users/47324",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to do a <code>SELECT</code> statement against the <code>wp_posts</code> and <code>wp_users</code> tables to get a list of all file names that qualify. Then manually delete them in the <code>uploads</code> folder. If it's on a Linux server I would create a <code>BASH</code> script to remove them all at once.</p>\n"
},
{
"answer_id": 238839,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>Here's some code which pulls all subscriber IDs, then pulls all attachments from those subscribers and attempts to delete them. If it can't delete them it'll write to the error log letting you know.</p>\n\n<pre><code>$subscribers = get_users( array(\n 'role' => 'subscriber',\n 'fields'=> 'ID',\n) );\n\nif( ! empty( $subscribers ) ) {\n\n $files = new WP_Query( array(\n 'post_type' => 'attachment',\n 'posts_per_page' => 200,\n 'author' => implode( ',', $subscribers ),\n 'fields' => 'ids',\n ) );\n\n if( ! empty( $files ) ) {\n foreach( $files->posts as $attachment_id ) {\n $deleted = wp_delete_attachment( $attachment_id, true );\n\n if( ! $deleted ) {\n error_log( \"Attachment {$deleted} Could Not Be Deleted!\" );\n }\n }\n }\n}\n</code></pre>\n\n<p>Odds are you'll have more attachments than your server can handle loading at the same time so you'll probably hit the 200 limit a few times but some page refreshes ( or an actual offset / pagination script ) will do the trick.</p>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55152/"
] |
I've inherited a very poorly designed WordPress site that in part uses BuddyPress for a directory type section. Users are able to upload profile images and 'product' images to their profile.
As a result, we now have roughly 20GB of images on the site and desperately need to cut back on this. When users, stop paying a membership fee to the charity running the site, the users role is changed from one of several custom roles back to the WP 'Subscriber' role.
My hope is that there is a fairly simple and accurate way to find images associated with a user or users profile and then delete these images if the users is has the 'Subscriber' role.
At present I've not tried anything along these lines, and am hoping someone with more WP dev experience might be able to give me some tips / suggestions on how to approach this.
Thanks in advance.
|
Here's some code which pulls all subscriber IDs, then pulls all attachments from those subscribers and attempts to delete them. If it can't delete them it'll write to the error log letting you know.
```
$subscribers = get_users( array(
'role' => 'subscriber',
'fields'=> 'ID',
) );
if( ! empty( $subscribers ) ) {
$files = new WP_Query( array(
'post_type' => 'attachment',
'posts_per_page' => 200,
'author' => implode( ',', $subscribers ),
'fields' => 'ids',
) );
if( ! empty( $files ) ) {
foreach( $files->posts as $attachment_id ) {
$deleted = wp_delete_attachment( $attachment_id, true );
if( ! $deleted ) {
error_log( "Attachment {$deleted} Could Not Be Deleted!" );
}
}
}
}
```
Odds are you'll have more attachments than your server can handle loading at the same time so you'll probably hit the 200 limit a few times but some page refreshes ( or an actual offset / pagination script ) will do the trick.
|
231,487 |
<p>Okay, I've got the following issue. I'm trying to send a mail in HTML format. I made a class that returns an HTML string, and that works great.</p>
<p>When I pass that html-mail as $message in my function, works also. But it will not send as html, but plain text.</p>
<p>Now I've tried the following things:</p>
<p>1)
<code>$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $message, $headers);</code></p>
<p>2)
<code>$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";</code></p>
<p>3)
<code>$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";</code></p>
<p>4)
<code>function wpse27856_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );</code></p>
<p>What else could it be?</p>
|
[
{
"answer_id": 231510,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 1,
"selected": false,
"text": "<p>Try this one. </p>\n\n<pre><code> add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );\n\n $to = '[email protected]';\n $subject = 'The subject';\n $body = 'The email body content';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n\n wp_mail( $to, $subject, $body , $headers);\n\n // Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578\n remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );\n\n function wpdocs_set_html_mail_content_type() {\n return 'text/html';\n }\n</code></pre>\n"
},
{
"answer_id": 231768,
"author": "Sam",
"author_id": 93282,
"author_profile": "https://wordpress.stackexchange.com/users/93282",
"pm_score": 0,
"selected": false,
"text": "<p>I personally wouldn't use the <code>wp_mail</code>-function, nor the php <code>mail</code>-function.\nBoth of them don't give you much control over your email. If you want to send HTML emails it's a good idea to send a plain text mail with it, so that users that are unable to read HTML emails can read your message too.</p>\n\n<p>Have a look on <code>phpmailer</code> that's a very good email sending class which gives you a lot of control over the email. You can add plain text to an HTML email, set a sender name instead of just having your email address and so on.</p>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92815/"
] |
Okay, I've got the following issue. I'm trying to send a mail in HTML format. I made a class that returns an HTML string, and that works great.
When I pass that html-mail as $message in my function, works also. But it will not send as html, but plain text.
Now I've tried the following things:
1)
`$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $message, $headers);`
2)
`$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";`
3)
`$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";`
4)
`function wpse27856_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );`
What else could it be?
|
Try this one.
```
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = '[email protected]';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body , $headers);
// Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
```
|
231,511 |
<p>I am struggling to get my settings page to save my options. I've got it showing up correctly and it hits the sanitize function</p>
<pre><code> register_setting(
'my_options', // Option group
'my_settings', // Option name
array($this, 'sanitize') // Sanitize
);
</code></pre>
<p>When I run the debugger on the sanitize function, $input is null:</p>
<pre><code>public function sanitize($input)
{
$new_input = array();
$new_input = $input;
//Sanitize the input actually
return $new_input;
}
</code></pre>
<p>The form itself is called like this:</p>
<pre><code><form id="my-admin-form" method="post" action="options.php">
<!-- Submission Notices -->
<div class="status-box notice notice-info" style="display: none;"></div>
<?php
settings_fields('my_options');
do_settings_sections('my_section');
submit_button();
?>
</form>
</code></pre>
|
[
{
"answer_id": 259603,
"author": "dhuyvetter",
"author_id": 86095,
"author_profile": "https://wordpress.stackexchange.com/users/86095",
"pm_score": 2,
"selected": false,
"text": "<p>It turned out to be nonce related: the form didn't have a nonce. Solved this by adding <code>wp_nonce_field</code> to the form.</p>\n"
},
{
"answer_id": 309926,
"author": "Mark Tierney",
"author_id": 147773,
"author_profile": "https://wordpress.stackexchange.com/users/147773",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem even after I added the nonce.</p>\n\n<p>The mistake I'd made was that the input names need to be an array, for example:</p>\n\n<pre><code><input id=\"my_option[key]\" type=\"text\" name=\"my_option[key]\" value=\"<?php !empty(my_option[key]) ? my_option[key] : NULL; ?>\">\n</code></pre>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231511",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86095/"
] |
I am struggling to get my settings page to save my options. I've got it showing up correctly and it hits the sanitize function
```
register_setting(
'my_options', // Option group
'my_settings', // Option name
array($this, 'sanitize') // Sanitize
);
```
When I run the debugger on the sanitize function, $input is null:
```
public function sanitize($input)
{
$new_input = array();
$new_input = $input;
//Sanitize the input actually
return $new_input;
}
```
The form itself is called like this:
```
<form id="my-admin-form" method="post" action="options.php">
<!-- Submission Notices -->
<div class="status-box notice notice-info" style="display: none;"></div>
<?php
settings_fields('my_options');
do_settings_sections('my_section');
submit_button();
?>
</form>
```
|
It turned out to be nonce related: the form didn't have a nonce. Solved this by adding `wp_nonce_field` to the form.
|
231,541 |
<p>I have a wordpress website where I post song lyrics.
I have written a wp query to list specific posts and order them by post views. However, I would like to order them by youtube views instead.</p>
<p>I have been able to get the youtube view counts for the posts (songs), the problem is ordering the posts with it. This is what the code looks like:-</p>
<pre><code><ul>
<?php $item=0; $loop = new WP_Query( array( 'post_type' => 'lyrics', 'date_query' => array( array( 'after' => '1 month ago' ) ), 'post_status'=> 'publish', 'meta_key' => 'post_view_count', 'orderby' => 'meta_value', 'posts_per_page' => 10 ) );
while ( $loop->have_posts() ) : $loop->the_post();
$song_name = get_the_title();
/*YOUTUBE QUERY HERE*/
$Yviews = 1234;
<li>
<?php echo esc_attr($song_name).' ('.$Yviews.' views)'; ?>
</li>
<?php endwhile; wp_reset_query(); ?>
</code></pre>
<p></p>
<p><strong>Things I Have Tried</strong></p>
<p>I created a custom field and tried updating the value (after the youtube code) with <code>update_post_meta(get_the_ID(), 'youtube_views', $Yviews);</code> and changed <code>'meta_key' => 'post_view_count'</code> to <code>'meta_key' => 'youtube_views'</code> but this either didn't work, or I wasn't doing it properly.</p>
<p>How do I achieve this?</p>
<p>PS: Ultimately, what I am trying to orderby is the sum of the post views and youtube views, but I can live without this.</p>
<p>Thanks in advance.</p>
<p>PS: I have omitted the youtube api query to make the code as simple as possible.</p>
|
[
{
"answer_id": 250277,
"author": "Marco",
"author_id": 109575,
"author_profile": "https://wordpress.stackexchange.com/users/109575",
"pm_score": 4,
"selected": true,
"text": "<p>I've had the same problem, and in my case it was the Wordpress cronjob. I was calling the wp-cron.php as a root cron job, and this script also generates the monthly upload folder.</p>\n\n<p>If you call wp-cron.php via cronjob you need to do this as the web server user (or i.e. in Plesk the site user and group psacln). The owner of the created monthly folder is always the user the wp-cron.php is called from.</p>\n"
},
{
"answer_id": 385182,
"author": "ZEST",
"author_id": 203446,
"author_profile": "https://wordpress.stackexchange.com/users/203446",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem, also a cronjob, but WP CLI was the issue. The cronjob was running a 'wp plugin' command every month, the 'wp plugin' command was creating the monthly folder owned by the same user that ran the cronjob -- root.</p>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86102/"
] |
I have a wordpress website where I post song lyrics.
I have written a wp query to list specific posts and order them by post views. However, I would like to order them by youtube views instead.
I have been able to get the youtube view counts for the posts (songs), the problem is ordering the posts with it. This is what the code looks like:-
```
<ul>
<?php $item=0; $loop = new WP_Query( array( 'post_type' => 'lyrics', 'date_query' => array( array( 'after' => '1 month ago' ) ), 'post_status'=> 'publish', 'meta_key' => 'post_view_count', 'orderby' => 'meta_value', 'posts_per_page' => 10 ) );
while ( $loop->have_posts() ) : $loop->the_post();
$song_name = get_the_title();
/*YOUTUBE QUERY HERE*/
$Yviews = 1234;
<li>
<?php echo esc_attr($song_name).' ('.$Yviews.' views)'; ?>
</li>
<?php endwhile; wp_reset_query(); ?>
```
**Things I Have Tried**
I created a custom field and tried updating the value (after the youtube code) with `update_post_meta(get_the_ID(), 'youtube_views', $Yviews);` and changed `'meta_key' => 'post_view_count'` to `'meta_key' => 'youtube_views'` but this either didn't work, or I wasn't doing it properly.
How do I achieve this?
PS: Ultimately, what I am trying to orderby is the sum of the post views and youtube views, but I can live without this.
Thanks in advance.
PS: I have omitted the youtube api query to make the code as simple as possible.
|
I've had the same problem, and in my case it was the Wordpress cronjob. I was calling the wp-cron.php as a root cron job, and this script also generates the monthly upload folder.
If you call wp-cron.php via cronjob you need to do this as the web server user (or i.e. in Plesk the site user and group psacln). The owner of the created monthly folder is always the user the wp-cron.php is called from.
|
231,548 |
<p>I just learned about child themes recently and was wondering if creating a child theme for every theme I create is necessary. I just find it weird how other themes work okay without child themes, and others do not. </p>
|
[
{
"answer_id": 231549,
"author": "Yarwood",
"author_id": 32655,
"author_profile": "https://wordpress.stackexchange.com/users/32655",
"pm_score": 1,
"selected": false,
"text": "<p>For me the rule of thumb is am I extending/revising an existing theme? If so I'll want to be able to update the theme (assuming it's well supported) without nuking all my changes. You can read more <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">here</a> in the codex.</p>\n\n<p>If I'm creating something custom I find it best to just use my own starter theme (or something like <a href=\"http://underscores.me/\" rel=\"nofollow\">Underscores</a>) and edit the theme itself.</p>\n"
},
{
"answer_id": 231570,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>Child themes are not the only way to extend a theme, not even the best.</p>\n\n<p>Many themes offer hooks: actions and filters. You can use these to change the output per plugin.</p>\n\n<p>Let’s say you have a theme named <em>Acme</em>, and its <code>index.php</code> contains the following code:</p>\n\n<pre><code>get_header();\n\ndo_action( 'acme.loop.before', 'index' );\n?>\n <div id=\"container\">\n <div id=\"content\" role=\"main\">\n\n <?php\n /*\n * Run the loop to output the posts.\n * If you want to overload this in a child theme then include a file\n * called loop-index.php and that will be used instead.\n */\n get_template_part( 'loop', 'index' );\n ?>\n </div><!-- #content -->\n </div><!-- #container -->\n\n<?php\ndo_action( 'acme.loop.after', 'index' );\n\ndo_action( 'acme.sidebar.before', 'index' );\nget_sidebar();\ndo_action( 'acme.sidebar.after', 'index' );\n\nget_footer();\n</code></pre>\n\n<p>Now you can write a small plugin to add wrappers (maybe for a second background image) around these specific areas:</p>\n\n<pre><code>add_action( 'acme.loop.before', function( $template ) {\n if ( 'index' === $template )\n print \"<div class='extra-background'>\";\n});\n\nadd_action( 'acme.loop.after', function( $template ) {\n if ( 'index' === $template )\n print \"</div>\";\n});\n</code></pre>\n\n<p>Add other, separate plugins for other modifications.</p>\n\n<p>This has four benefits: </p>\n\n<ol>\n<li><p>You can turn off the extra behavior in your plugin administration if you don't want it anymore. In contrast to child themes, you do that for each plugin separately, you don't have to turn every customization like you do when you have only one child theme.</p></li>\n<li><p>It is much faster than a child theme, because when WordPress is searching for a template and it cannot find it, it will search in both, child and parent themes. That cannot happen when there is no child theme.</p></li>\n<li><p>It is easier to debug when something goes wrong. With child themes, it is hard to see where an error is coming from, child or parent theme. Or both, that's extra fun.</p></li>\n<li><p>Safe updates. Sometimes, when you update a parent theme, the child theme doesn't work anymore, or worse: it works differently. It might even raise a fatal error, because you are using a function in the child theme that isn't available in the parent theme anymore.</p></li>\n</ol>\n\n<p><strong>Summary:</strong> Use hooks whenever you can, use a child theme only if the parent theme doesn't offer a good hook. Ask the theme author to add the missing hook. If you can offer a valid use case, I am sure s/he will implement it.</p>\n"
}
] |
2016/07/05
|
[
"https://wordpress.stackexchange.com/questions/231548",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68815/"
] |
I just learned about child themes recently and was wondering if creating a child theme for every theme I create is necessary. I just find it weird how other themes work okay without child themes, and others do not.
|
Child themes are not the only way to extend a theme, not even the best.
Many themes offer hooks: actions and filters. You can use these to change the output per plugin.
Let’s say you have a theme named *Acme*, and its `index.php` contains the following code:
```
get_header();
do_action( 'acme.loop.before', 'index' );
?>
<div id="container">
<div id="content" role="main">
<?php
/*
* Run the loop to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-index.php and that will be used instead.
*/
get_template_part( 'loop', 'index' );
?>
</div><!-- #content -->
</div><!-- #container -->
<?php
do_action( 'acme.loop.after', 'index' );
do_action( 'acme.sidebar.before', 'index' );
get_sidebar();
do_action( 'acme.sidebar.after', 'index' );
get_footer();
```
Now you can write a small plugin to add wrappers (maybe for a second background image) around these specific areas:
```
add_action( 'acme.loop.before', function( $template ) {
if ( 'index' === $template )
print "<div class='extra-background'>";
});
add_action( 'acme.loop.after', function( $template ) {
if ( 'index' === $template )
print "</div>";
});
```
Add other, separate plugins for other modifications.
This has four benefits:
1. You can turn off the extra behavior in your plugin administration if you don't want it anymore. In contrast to child themes, you do that for each plugin separately, you don't have to turn every customization like you do when you have only one child theme.
2. It is much faster than a child theme, because when WordPress is searching for a template and it cannot find it, it will search in both, child and parent themes. That cannot happen when there is no child theme.
3. It is easier to debug when something goes wrong. With child themes, it is hard to see where an error is coming from, child or parent theme. Or both, that's extra fun.
4. Safe updates. Sometimes, when you update a parent theme, the child theme doesn't work anymore, or worse: it works differently. It might even raise a fatal error, because you are using a function in the child theme that isn't available in the parent theme anymore.
**Summary:** Use hooks whenever you can, use a child theme only if the parent theme doesn't offer a good hook. Ask the theme author to add the missing hook. If you can offer a valid use case, I am sure s/he will implement it.
|
231,557 |
<p>I'm trying to create a custom widget to display contributing authors for the current category being viewed on a WordPress site. I have the following PHP code:</p>
<pre><code><?php
if (is_category()) {
?>
// Grab posts from the current category
<?php
$current_category = single_cat_title(“”, false);
$author_array = array();
$args = array(
‘numberposts’ => -1,
‘category_name’ => $current_category,
‘orderby’ => ‘author’,
‘order’ => ‘ASC’
);
// Get the posts in the array and create an array of the authors
$cat_posts = get_posts($args);
foreach ($cat_posts as $cat_post):
if (!in_array($cat_post->post_author, $author_array)) {
$author_array[] = $cat_post->post_author;
}
endforeach;
// Get the author information and build the output
foreach ($author_array as $author):
$auth = get_userdata($author)->display_name;
$auth_link = get_userdata($author)->user_login;
echo "<a href='/author/'" . $auth_link . "'>" . $auth . "</a>" . '<br \/>';
endforeach;
// Testing to make sure the current category is being pulled correctly
echo $current_category;
?>
<?php
}
?>
</code></pre>
<p>It's displaying authors from the site, but they're not changing from category to category - the same three are displayed in each section. The test statement at the end of the code block is working as expected - the displayed category in the widget matches the URI category.</p>
<p>Any thoughts on where I went wrong in creating the author array?</p>
|
[
{
"answer_id": 231558,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\nif( is_category() ) {\n global $wp_query;\n $term_obj = $wp_query->get_queried_object();\n $author_array = array();\n $args = array(\n 'posts_per_page' => -1,\n 'category' => $term_obj->term_id,\n 'orderby' => 'author',\n 'order' => 'ASC'\n ); \n\n // Get the posts in the array and create an array of the authors\n $cat_posts = get_posts( $args );\n foreach ( $cat_posts as $cat_post ):\n if ( ! in_array( $cat_post->post_author, $author_array ) ) {\n $author_array[] = $cat_post->post_author;\n }\n endforeach;\n\n // Get the author information and build the output\n foreach ( $author_array as $author ):\n $auth = get_userdata($author)->display_name;\n $auth_link = get_userdata($author)->user_login;\n printf( '<a href=\"/author/%s\">%s</a><br />', $auth_link, $auth );\n endforeach;\n}\n?>\n</code></pre>\n\n<p>Explaining the Code here:</p>\n\n<ol>\n<li>Checking category archive page by <strong>is_category()</strong> conditional tag</li>\n<li>Assign global variable <strong>global $wp_query;</strong></li>\n<li>Now getting the queried object by <strong>$wp_query->get_queried_object()</strong> function</li>\n<li>Creating the args array. I am using category ID (<strong>$term_obj->term_id</strong>) not category name. </li>\n<li>Fetching the all posts of current category by <strong>get_posts()</strong> function</li>\n<li>Now creating the unique authors array. </li>\n<li>Lastly displaying the authors list by <strong>printf()</strong> function.</li>\n</ol>\n"
},
{
"answer_id": 231588,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>This can become a quite an expensive operation which can seriously damage page load time. At this stage, your code is quite expensive. Lets look a better way to tackle this issue.</p>\n\n<p>What we need to do is to minimize the time spend in db, and to do this, we will only get the info we need, that is the <code>post_author</code> property of the post object. As we now, there is no native way to just get the <code>post_author</code> property from the db with <code>WP_Query</code>, we only have the possibility to get the complete object or just the post <code>ID</code>'s. To alter the behavior (<em>and the generated SQL</em>), we will make use of the <code>posts_fields</code> filter in which we can command the SQL query to just return the <code>post_author</code> field, which will save us a ton in time spend in the db as we only get what we need.</p>\n\n<p>Secondly, to improve performance, we will tell <code>WP_Query</code> to not cache any post data or post term and post meta data. As we will not be needing any meta data or post term data, we can simply just ask <code>WP_Query</code> to not query these and cache them for later use, this also saves us a lot of extra time spend in db, time to add this data in cache, and we will also save on db queries. </p>\n\n<p>Lets put this all in code: (<strong><em>NOTE:</strong> All code is untested and require PHP 5.4+</em>)</p>\n\n<h2><code>posts_fields</code> FILTER</h2>\n\n<pre><code>add_filter( 'posts_fields', function ( $fields, \\WP_Query $q ) use ( &$wpdb )\n{\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Only target a query where the new wpse_post_author parameter is set to true\n if ( true === $q->get( 'wpse_post_author' ) ) {\n // Only get the post_author column\n $fields = \"\n $wpdb->posts.post_author\n \";\n }\n\n return $fields;\n}, 10, 2);\n</code></pre>\n\n<p>You'll notice that we have a custom trigger called <code>wpse_post_author</code>. Whenever we pass a value of <code>true</code> to that custom trigger, our filter will fire. </p>\n\n<h2><code>get_posts()</code> QUERY</h2>\n\n<p>By default, <code>get_posts()</code> passes <code>suppress_filters=true</code> to <code>WP_Query</code> as to avoid filters acting on <code>get_posts()</code>, so in order to get our filter to work, we need to set that back to true. </p>\n\n<p>Just another note, to get the current category reliably, use <code>$GLOBALS['wp_the_query']->get_queried_object()</code> and <code>$GLOBALS['wp_the_query']->get_queried_object_id()</code> for the category ID</p>\n\n<pre><code>if ( is_category() ) {\n $current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );\n\n $args = [\n 'wpse_post_author' => true, // To trigger our filter\n 'posts_per_page' => -1,\n 'orderby' => 'author',\n 'order' => 'ASC',\n 'suppress_filters' => false, // Allow filters to alter query\n 'cache_results' => false, // Do not cache posts\n 'update_post_meta_cache' => false, // Do not cache custom field data\n 'update_post_term_cache' => false, // Do not cache post terms\n 'tax_query' => [\n [\n 'taxonomy' => $current_category->taxonomy,\n 'terms' => $current_category->term_id,\n 'include_children' => true\n ]\n ]\n ];\n $posts_array = get_posts( $args );\n\n if ( $posts_array ) {\n // Get all the post authors from the posts\n $post_author_ids = wp_list_pluck( $posts_array, 'post_author' );\n\n // Get a unique array of ids\n $post_author_ids = array_unique( $post_author_ids );\n\n // NOW WE CAN DO SOMETHING WITH THE ID'S, SEE BELOW TO INCLUDE HERE\n }\n}\n</code></pre>\n\n<p>As you can see, I used a <code>tax_query</code>, this is personal preference due to the flexibility of it, and also, you can reuse the code on any term page with no need to modify it. In this case, you only need to change the <code>is_category()</code> condition. </p>\n\n<p>In my <code>tax_query</code> I have set <code>include_children</code> to <code>true</code>, which means that <code>WP_Query</code> will get posts from the current category and the posts that belongs to the child categories of the category being viewed. This is default behavior for all hierarchical term pages. If you really just need authors from the category being viewed, set <code>include_children</code> to <code>false</code></p>\n\n<h2>QUERYING THE AUTHORS</h2>\n\n<p>If you do a <code>var_dump( $post_author_ids )</code>, you will see that you have an array of post author ids. Now, instead of looping through each and every ID, you can just pass this array of id's to <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\"><code>WP_User_Query</code></a>, and then loop through the results from that query.</p>\n\n<pre><code>$user_args = [\n 'include' => $post_author_ids\n];\n$user_query = new \\WP_User_Query( $user_args );\nvar_dump( $user_query->results ); // For debugging purposes\n\nif ( $user_query->results ) {\n foreach ( $user_query->results as $user ) {\n echo $user->display_name;\n }\n}\n</code></pre>\n\n<p>We can take this even further and save everything in a transient, which will have us ending up only 2 db queries in =/- 0.002s. </p>\n\n<h2>THE TRANSIENT</h2>\n\n<p>To set a unique transient name, we will use the term object to create a unique name</p>\n\n<pre><code>if ( is_category() ) {\n $current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );\n $transient_name = 'wpse231557_' . md5( json_encode( $current_category ) );\n\n // Check if transient is set\n if ( false === ( $user_query = get_transient( $transient_name ) ) ) {\n\n // Our code above\n\n // Set the transient for 3 days, adjust as needed\n set_transient( $transient_name, $user_query, 72 * HOUR_IN_SECONDS );\n }\n\n // Run your foreach loop to display users\n}\n</code></pre>\n\n<p><strong>FLUSHING THE TRANSIENT</strong></p>\n\n<p>We can flush the transient whenever a new post is publish or when a post is edited, deleted, undeleted, etc. For this we can use the <code>transition_post_status</code> hook. You can also adjust it to fire only when certain things happens, like only when a new post is published. Anyways, here is the hook which will fire when anything happens to the post</p>\n\n<pre><code>add_action( 'transition_post_status', function () use ( &$wpdb )\n{\n $wpdb->query( \"DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_wpse231557_%')\" );\n $wpdb->query( \"DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_wpse231557_%')\" );\n});\n</code></pre>\n\n<h1>ALL TOGETHER NOW!!!</h1>\n\n<p>In a functions type file</p>\n\n<pre><code>add_filter( 'posts_fields', function ( $fields, \\WP_Query $q ) use ( &$wpdb )\n{\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Only target a query where the new wpse_post_author parameter is set to true\n if ( true === $q->get( 'wpse_post_author' ) ) {\n // Only get the post_author column\n $fields = \"\n $wpdb->posts.post_author\n \";\n }\n\n return $fields;\n}, 10, 2);\n\nadd_action( 'transition_post_status', function () use ( &$wpdb )\n{\n $wpdb->query( \"DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_wpse231557_%')\" );\n $wpdb->query( \"DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_wpse231557_%')\" );\n});\n</code></pre>\n\n<p>In your widget</p>\n\n<pre><code>if ( is_category() ) {\n $current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );\n $transient_name = 'wpse231557_' . md5( json_encode( $current_category ) );\n\n // Check if transient is set\n if ( false === ( $user_query = get_transient( $transient_name ) ) ) {\n\n $args = [\n 'wpse_post_author' => true, // To trigger our filter\n 'posts_per_page' => -1,\n 'orderby' => 'author',\n 'order' => 'ASC',\n 'suppress_filters' => false, // Allow filters to alter query\n 'cache_results' => false, // Do not cache posts\n 'update_post_meta_cache' => false, // Do not cache custom field data\n 'update_post_term_cache' => false, // Do not cache post terms\n 'tax_query' => [\n [\n 'taxonomy' => $current_category->taxonomy,\n 'terms' => $current_category->term_id,\n 'include_children' => true\n ]\n ]\n ];\n $posts_array = get_posts( $args );\n\n $user_query = false;\n\n if ( $posts_array ) {\n // Get all the post authors from the posts\n $post_author_ids = wp_list_pluck( $posts_array, 'post_author' );\n\n // Get a unique array of ids\n $post_author_ids = array_unique( $post_author_ids );\n\n $user_args = [\n 'include' => $post_author_ids\n ];\n $user_query = new \\WP_User_Query( $user_args );\n }\n\n // Set the transient for 3 days, adjust as needed\n set_transient( $transient_name, $user_query, 72 * HOUR_IN_SECONDS );\n }\n\n if ( false !== $user_query\n && $user_query->results \n ) {\n foreach ( $user_query->results as $user ) {\n echo $user->display_name;\n }\n }\n}\n</code></pre>\n\n<h1>EDIT</h1>\n\n<p>All code is now tested and works as expected</p>\n"
}
] |
2016/07/06
|
[
"https://wordpress.stackexchange.com/questions/231557",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76765/"
] |
I'm trying to create a custom widget to display contributing authors for the current category being viewed on a WordPress site. I have the following PHP code:
```
<?php
if (is_category()) {
?>
// Grab posts from the current category
<?php
$current_category = single_cat_title(“”, false);
$author_array = array();
$args = array(
‘numberposts’ => -1,
‘category_name’ => $current_category,
‘orderby’ => ‘author’,
‘order’ => ‘ASC’
);
// Get the posts in the array and create an array of the authors
$cat_posts = get_posts($args);
foreach ($cat_posts as $cat_post):
if (!in_array($cat_post->post_author, $author_array)) {
$author_array[] = $cat_post->post_author;
}
endforeach;
// Get the author information and build the output
foreach ($author_array as $author):
$auth = get_userdata($author)->display_name;
$auth_link = get_userdata($author)->user_login;
echo "<a href='/author/'" . $auth_link . "'>" . $auth . "</a>" . '<br \/>';
endforeach;
// Testing to make sure the current category is being pulled correctly
echo $current_category;
?>
<?php
}
?>
```
It's displaying authors from the site, but they're not changing from category to category - the same three are displayed in each section. The test statement at the end of the code block is working as expected - the displayed category in the widget matches the URI category.
Any thoughts on where I went wrong in creating the author array?
|
This can become a quite an expensive operation which can seriously damage page load time. At this stage, your code is quite expensive. Lets look a better way to tackle this issue.
What we need to do is to minimize the time spend in db, and to do this, we will only get the info we need, that is the `post_author` property of the post object. As we now, there is no native way to just get the `post_author` property from the db with `WP_Query`, we only have the possibility to get the complete object or just the post `ID`'s. To alter the behavior (*and the generated SQL*), we will make use of the `posts_fields` filter in which we can command the SQL query to just return the `post_author` field, which will save us a ton in time spend in the db as we only get what we need.
Secondly, to improve performance, we will tell `WP_Query` to not cache any post data or post term and post meta data. As we will not be needing any meta data or post term data, we can simply just ask `WP_Query` to not query these and cache them for later use, this also saves us a lot of extra time spend in db, time to add this data in cache, and we will also save on db queries.
Lets put this all in code: (***NOTE:*** All code is untested and require PHP 5.4+)
`posts_fields` FILTER
---------------------
```
add_filter( 'posts_fields', function ( $fields, \WP_Query $q ) use ( &$wpdb )
{
remove_filter( current_filter(), __FUNCTION__ );
// Only target a query where the new wpse_post_author parameter is set to true
if ( true === $q->get( 'wpse_post_author' ) ) {
// Only get the post_author column
$fields = "
$wpdb->posts.post_author
";
}
return $fields;
}, 10, 2);
```
You'll notice that we have a custom trigger called `wpse_post_author`. Whenever we pass a value of `true` to that custom trigger, our filter will fire.
`get_posts()` QUERY
-------------------
By default, `get_posts()` passes `suppress_filters=true` to `WP_Query` as to avoid filters acting on `get_posts()`, so in order to get our filter to work, we need to set that back to true.
Just another note, to get the current category reliably, use `$GLOBALS['wp_the_query']->get_queried_object()` and `$GLOBALS['wp_the_query']->get_queried_object_id()` for the category ID
```
if ( is_category() ) {
$current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );
$args = [
'wpse_post_author' => true, // To trigger our filter
'posts_per_page' => -1,
'orderby' => 'author',
'order' => 'ASC',
'suppress_filters' => false, // Allow filters to alter query
'cache_results' => false, // Do not cache posts
'update_post_meta_cache' => false, // Do not cache custom field data
'update_post_term_cache' => false, // Do not cache post terms
'tax_query' => [
[
'taxonomy' => $current_category->taxonomy,
'terms' => $current_category->term_id,
'include_children' => true
]
]
];
$posts_array = get_posts( $args );
if ( $posts_array ) {
// Get all the post authors from the posts
$post_author_ids = wp_list_pluck( $posts_array, 'post_author' );
// Get a unique array of ids
$post_author_ids = array_unique( $post_author_ids );
// NOW WE CAN DO SOMETHING WITH THE ID'S, SEE BELOW TO INCLUDE HERE
}
}
```
As you can see, I used a `tax_query`, this is personal preference due to the flexibility of it, and also, you can reuse the code on any term page with no need to modify it. In this case, you only need to change the `is_category()` condition.
In my `tax_query` I have set `include_children` to `true`, which means that `WP_Query` will get posts from the current category and the posts that belongs to the child categories of the category being viewed. This is default behavior for all hierarchical term pages. If you really just need authors from the category being viewed, set `include_children` to `false`
QUERYING THE AUTHORS
--------------------
If you do a `var_dump( $post_author_ids )`, you will see that you have an array of post author ids. Now, instead of looping through each and every ID, you can just pass this array of id's to [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query), and then loop through the results from that query.
```
$user_args = [
'include' => $post_author_ids
];
$user_query = new \WP_User_Query( $user_args );
var_dump( $user_query->results ); // For debugging purposes
if ( $user_query->results ) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
}
```
We can take this even further and save everything in a transient, which will have us ending up only 2 db queries in =/- 0.002s.
THE TRANSIENT
-------------
To set a unique transient name, we will use the term object to create a unique name
```
if ( is_category() ) {
$current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );
$transient_name = 'wpse231557_' . md5( json_encode( $current_category ) );
// Check if transient is set
if ( false === ( $user_query = get_transient( $transient_name ) ) ) {
// Our code above
// Set the transient for 3 days, adjust as needed
set_transient( $transient_name, $user_query, 72 * HOUR_IN_SECONDS );
}
// Run your foreach loop to display users
}
```
**FLUSHING THE TRANSIENT**
We can flush the transient whenever a new post is publish or when a post is edited, deleted, undeleted, etc. For this we can use the `transition_post_status` hook. You can also adjust it to fire only when certain things happens, like only when a new post is published. Anyways, here is the hook which will fire when anything happens to the post
```
add_action( 'transition_post_status', function () use ( &$wpdb )
{
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_wpse231557_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_wpse231557_%')" );
});
```
ALL TOGETHER NOW!!!
===================
In a functions type file
```
add_filter( 'posts_fields', function ( $fields, \WP_Query $q ) use ( &$wpdb )
{
remove_filter( current_filter(), __FUNCTION__ );
// Only target a query where the new wpse_post_author parameter is set to true
if ( true === $q->get( 'wpse_post_author' ) ) {
// Only get the post_author column
$fields = "
$wpdb->posts.post_author
";
}
return $fields;
}, 10, 2);
add_action( 'transition_post_status', function () use ( &$wpdb )
{
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_wpse231557_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_wpse231557_%')" );
});
```
In your widget
```
if ( is_category() ) {
$current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );
$transient_name = 'wpse231557_' . md5( json_encode( $current_category ) );
// Check if transient is set
if ( false === ( $user_query = get_transient( $transient_name ) ) ) {
$args = [
'wpse_post_author' => true, // To trigger our filter
'posts_per_page' => -1,
'orderby' => 'author',
'order' => 'ASC',
'suppress_filters' => false, // Allow filters to alter query
'cache_results' => false, // Do not cache posts
'update_post_meta_cache' => false, // Do not cache custom field data
'update_post_term_cache' => false, // Do not cache post terms
'tax_query' => [
[
'taxonomy' => $current_category->taxonomy,
'terms' => $current_category->term_id,
'include_children' => true
]
]
];
$posts_array = get_posts( $args );
$user_query = false;
if ( $posts_array ) {
// Get all the post authors from the posts
$post_author_ids = wp_list_pluck( $posts_array, 'post_author' );
// Get a unique array of ids
$post_author_ids = array_unique( $post_author_ids );
$user_args = [
'include' => $post_author_ids
];
$user_query = new \WP_User_Query( $user_args );
}
// Set the transient for 3 days, adjust as needed
set_transient( $transient_name, $user_query, 72 * HOUR_IN_SECONDS );
}
if ( false !== $user_query
&& $user_query->results
) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
}
}
```
EDIT
====
All code is now tested and works as expected
|
231,589 |
<p><br />
I've been trying to redirect a page but with no success. <br />
My purpose is to redirect <code>example.com/me/name</code> to <code>example.com/me?n=name</code><br />
I've tried with <code>add_rewrite_rule</code>, write conditions in .htaccess, but nothing worked.
Any clue?
<br/>
Edit:<br/>
The full htaccess code is this:<br/></p>
<pre><code># 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
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
</code></pre>
<p>Edit 2:<br/>
The code for redirect I was trying to use is this:<br/></p>
<pre><code>#RewriteRule (http://example.com/me/*) http://example.com/me?n=$1
</code></pre>
<p><br/><br/>
Edit 3:<br/>
The "name" in the code does not stay the same, it is variable depending on person. It can be Ash, George, Mike, whatever.</p>
|
[
{
"answer_id": 231581,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>This is an interesting question, though a bit too broad for a Q&A model. Here is what I would do:</p>\n\n<ol>\n<li>Create a custom post type, where each post is a block of content</li>\n<li>Create a second custom post type for pages that are assembled from blocks of code. In stead of a content field, create ten drop down fields (or more if there are more blocks possible on a page). For the <code>select</code> options in the dropdown, take the title of all posts in the first custom post type. In this way any new block of content will automatically become available for assembly.</li>\n<li>Create a template for the second post type, that loops through all drop down fields and assembles the content from the first custom posts.</li>\n</ol>\n"
},
{
"answer_id": 231686,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>While shortcodes by themselves are linked to functions, I think you could use them effectively in combination with templates and a metabox for their input data. eg:</p>\n\n<pre><code>add_shortcode('content-box','content_box_function');\nfunction content_box_function() {\n global $post;\n $title = get_post_meta($post->ID,'_content_box_title',true);\n $content = get_post_meta($post->ID,'_content_box_content',true);\n get_template_part('templates/content','box');\n}\n</code></pre>\n\n<p>/wp-content/themes/<em>theme-slug</em>/templates/content-box.php</p>\n\n<pre><code><div class=\"content-box-container\">\n <div class=\"content-box\">\n <h3 class=\"content-box-title\"><?php echo $title; ?></h3>\n <div class=\"content-box-content\"><?php echo $content; ?></div>\n </div>\n</div>\n</code></pre>\n\n<p>Then add a metabox to the post writing screen to allow the user to select/define the meta values to go with the keys you are using for each content block shortcode.</p>\n\n<p>Gives you the advantage of allowing the shortcode to be ordered/placed anywhere in the content, and still have other content there as needed be, but the templating (and related styling) could be worked out already for the predefined content block types.</p>\n"
},
{
"answer_id": 231712,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 1,
"selected": false,
"text": "<p>You could consider using the page templates. For the example im going to use a contact page. \"contact-page.php\" </p>\n\n<p>You can then write in the code you need for the template. To keep the flexibility look up how to use the Customizer (if you're not familiar with it) and use this in the template page to let the admin modify the page content without having to look at the code. This is how I've done my templates.</p>\n"
},
{
"answer_id": 238571,
"author": "sven",
"author_id": 97909,
"author_profile": "https://wordpress.stackexchange.com/users/97909",
"pm_score": 1,
"selected": true,
"text": "<p>I evaluated the different options and went with a plugin \"Page Builder\". While the technical aspects are not great (e.g. data persisting: all content gets serialized) is was the only option to give me enough flexibility and enough comfort so that the customer could make changes to the structure of each page.</p>\n\n<p>Migrating from dev to stage to live was also a pain due to the serializing and only possible with yet another plugin (duplicator).</p>\n\n<p>Thanks everyone for the input!</p>\n"
}
] |
2016/07/06
|
[
"https://wordpress.stackexchange.com/questions/231589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97913/"
] |
I've been trying to redirect a page but with no success.
My purpose is to redirect `example.com/me/name` to `example.com/me?n=name`
I've tried with `add_rewrite_rule`, write conditions in .htaccess, but nothing worked.
Any clue?
Edit:
The full htaccess code is this:
```
# 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
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
```
Edit 2:
The code for redirect I was trying to use is this:
```
#RewriteRule (http://example.com/me/*) http://example.com/me?n=$1
```
Edit 3:
The "name" in the code does not stay the same, it is variable depending on person. It can be Ash, George, Mike, whatever.
|
I evaluated the different options and went with a plugin "Page Builder". While the technical aspects are not great (e.g. data persisting: all content gets serialized) is was the only option to give me enough flexibility and enough comfort so that the customer could make changes to the structure of each page.
Migrating from dev to stage to live was also a pain due to the serializing and only possible with yet another plugin (duplicator).
Thanks everyone for the input!
|
231,597 |
<p>Following <a href="http://keithclark.co.uk/articles/loading-css-without-blocking-render/" rel="nofollow">Keith Clarks advice</a>, i'd like to load my fonts asynchronously. I try to achieve that by adding: </p>
<pre><code>wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );
wp_style_add_data( 'font-awesome', 'onload', 'if(media!=\'all\')media=\'all\'');
</code></pre>
<p>to my <code>scripts.php</code> file, but apparently this argument is not well taken by that function, because there is no onload attribute. How properly can I do that in WordPress?</p>
|
[
{
"answer_id": 231603,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": false,
"text": "<p>We can use <a href=\"https://developer.wordpress.org/reference/hooks/style_loader_tag/\" rel=\"noreferrer\"><code>style_loader_tag</code></a> filter to filter the link that is being output.</p>\n\n<p>Here is the filter:</p>\n\n<pre><code>$tag = apply_filters( 'style_loader_tag', \"<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\\n\", $handle, $href, $media);\n</code></pre>\n\n<p>Here the link $handle for which you want to add attribute is <strong><code>font-awesome</code></strong> so if the handle, so you can replace <code>font-awesome-css</code> with extra info.</p>\n\n<pre><code>add_filter('style_loader_tag', 'wpse_231597_style_loader_tag');\n\nfunction wpse_231597_style_loader_tag($tag){\n\n $tag = preg_replace(\"/id='font-awesome-css'/\", \"id='font-awesome-css' online=\\\"if(media!='all')media='all'\\\"\", $tag);\n\n return $tag;\n}\n</code></pre>\n"
},
{
"answer_id": 320095,
"author": "Remzi Cavdar",
"author_id": 149484,
"author_profile": "https://wordpress.stackexchange.com/users/149484",
"pm_score": 2,
"selected": false,
"text": "<p>I really understand both of you, but I would like to point out that following <a href=\"https://keithclark.co.uk/articles/loading-css-without-blocking-render/\" rel=\"nofollow noreferrer\">Keith Clark's advice</a> is just following another bad practice. I also understand that this is asked and answered in 2016 and that most things change for better or worse.<br></p>\n\n<p>If you need to delay a stylesheet, then I would recommend you the following:</p>\n\n<pre><code>// I use get_footer to put my stylesheets in the footer\nfunction add_footer_styles() {\n // Example loading external stylesheet, could be used in both a theme and/or plugin\n wp_enqueue_style( 'font-awesome-5', 'https://use.fontawesome.com/releases/v5.5.0/css/all.css', array(), null );\n\n // Example theme\n wp_enqueue_style( 'font-awesome-5', get_theme_file_uri( '/assets/css/fontawesome.min.css' ), array(), null );\n\n // Example plugin\n wp_enqueue_style( 'font-awesome-5', plugins_url( '/assets/css/fontawesome.min.css', __FILE__ ), array(), null );\n};\nadd_action( 'get_footer', 'add_footer_styles' );\n</code></pre>\n\n<p><br><br>\n<strong><a href=\"https://hacks.mozilla.org/2015/09/subresource-integrity-in-firefox-43/\" rel=\"nofollow noreferrer\">Integrity and crossorigin</a></strong><br>\nIf you add Font Awesome 5 externally I would also recommend using <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity\" rel=\"nofollow noreferrer\">integrity</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\" rel=\"nofollow noreferrer\">crossorigin</a>, see my other answer for a more detailed take on adding attributes: <a href=\"https://wordpress.stackexchange.com/questions/317035/how-to-add-crossorigin-and-integrity-to-wp-register-style-font-awesome-5\">How to add crossorigin and integrity to wp_register_style? (Font Awesome 5)</a></p>\n\n<pre><code>function add_font_awesome_5_cdn_attributes( $html, $handle ) {\n if ( 'font-awesome-5' === $handle ) {\n return str_replace( \"media='all'\", \"media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'\", $html );\n }\n return $html;\n}\nadd_filter( 'style_loader_tag', 'add_font_awesome_5_cdn_attributes', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 383560,
"author": "kwaves",
"author_id": 202083,
"author_profile": "https://wordpress.stackexchange.com/users/202083",
"pm_score": 2,
"selected": false,
"text": "<p>If you're going to be deferring more than one stylesheet, I've found this approach to be fairly reusable.</p>\n<ol>\n<li>Put this somewhere:</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>function _changeme_defer_css( $html, $handle ) {\n\n $deferred_stylesheets = apply_filters( 'changeme_deferred_stylesheets', array() );\n\n if ( in_array( $handle, $deferred_stylesheets, true ) ) {\n return str_replace( 'media=\\'all\\'', 'media="print" onload="this.media=\\'all\\'"', $html );\n } else {\n return $html;\n }\n\n}\nadd_filter( 'style_loader_tag', '_changeme_defer_css', 10, 2 );\n</code></pre>\n<ol start=\"2\">\n<li>Load your font as you normally would:</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>function _changeme_load_font_awesome() {\n wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );\n}\nadd_filter( 'wp_enqueue_scripts', '_changeme_load_font_awesome' );\n</code></pre>\n<ol start=\"3\">\n<li>Defer it like so:</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'changeme_deferred_stylesheets', function( $handles ) {\n $handles[] = 'font-awesome';\n return $handles;\n}, 10, 1 );\n</code></pre>\n<ol start=\"4\">\n<li>If you want to make sure it only impacts the public-facing side of your site, and not <code>wp-admin</code>, you could add a check for <code>! is_admin()</code> as well (especially for commonly-used libraries like <code>Font Awesome</code> or <code>Select2</code>):</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'changeme_deferred_stylesheets', function( $handles ) {\n if ( ! is_admin() ) {\n $handles[] = 'font-awesome';\n }\n return $handles;\n}, 10, 1 );\n</code></pre>\n<p>I also updated the <code>onload</code> approach based on Scott Jehl's <a href=\"https://www.filamentgroup.com/lab/load-css-simpler/\" rel=\"nofollow noreferrer\">The Simplest Way to Load CSS Asynchronously</a> (2019) but if you're going to do this, you may also want to read the "Async CSS" passage from Harry Roberts's <a href=\"https://csswizardry.com/2020/05/the-fastest-google-fonts/\" rel=\"nofollow noreferrer\">The Fastest Google Fonts</a> (2020) to see why he recommends preloading as well.</p>\n"
}
] |
2016/07/06
|
[
"https://wordpress.stackexchange.com/questions/231597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97916/"
] |
Following [Keith Clarks advice](http://keithclark.co.uk/articles/loading-css-without-blocking-render/), i'd like to load my fonts asynchronously. I try to achieve that by adding:
```
wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );
wp_style_add_data( 'font-awesome', 'onload', 'if(media!=\'all\')media=\'all\'');
```
to my `scripts.php` file, but apparently this argument is not well taken by that function, because there is no onload attribute. How properly can I do that in WordPress?
|
We can use [`style_loader_tag`](https://developer.wordpress.org/reference/hooks/style_loader_tag/) filter to filter the link that is being output.
Here is the filter:
```
$tag = apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle, $href, $media);
```
Here the link $handle for which you want to add attribute is **`font-awesome`** so if the handle, so you can replace `font-awesome-css` with extra info.
```
add_filter('style_loader_tag', 'wpse_231597_style_loader_tag');
function wpse_231597_style_loader_tag($tag){
$tag = preg_replace("/id='font-awesome-css'/", "id='font-awesome-css' online=\"if(media!='all')media='all'\"", $tag);
return $tag;
}
```
|
231,623 |
<p>A site I'm currently working on has a page structure like this</p>
<pre><code>About Us
|
|_People
| |
| _ Person 1
| _ Person 2
| _ Person 3
|... etc ...
</code></pre>
<p>Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.</p>
<p>I know how to create a custom page template for one specific page, i.e. page-<em>slug</em>.php, but I want to use one page template for all of those subpages.</p>
<p>What would be the easiest way to accomplish this?</p>
|
[
{
"answer_id": 231625,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way would be to create a <a href=\"https://codex.wordpress.org/Post_Types#Custom_Post_Types\" rel=\"nofollow\">custom post type</a> 'person', in which you include the custom fields. The <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow\">WordPress template hierarchy</a> would then ensure that the <code>single-person.php</code> template is used for those posts.</p>\n"
},
{
"answer_id": 231626,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You can always make use of the <code>page_template</code> filter to tell WordPress to use a specific page template for all child pages of a certain parent. It is as easy as creating a special page template, lets call it <code>page-wpse-person.php</code>.</p>\n\n<p>Now it is as easy as including that template whenever a child page of <code>people</code> is being viewed. For the sake of example, lets say the page ID of <code>people</code> is <code>10</code></p>\n\n<pre><code>add_filter( 'page_template', function ( $template ) use ( &$post )\n{\n // Check if we have page which is a child of people, ID 10\n if ( 10 !== $post->post_parent )\n return $template;\n\n // This is a person page, child of people, try to locate our custom page\n $locate_template = locate_template( 'page-wpse-person.php' );\n\n // Check if our template was found, if not, bail\n if ( !$locate_template )\n return $template;\n\n return $locate_template;\n});\n</code></pre>\n"
}
] |
2016/07/06
|
[
"https://wordpress.stackexchange.com/questions/231623",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37750/"
] |
A site I'm currently working on has a page structure like this
```
About Us
|
|_People
| |
| _ Person 1
| _ Person 2
| _ Person 3
|... etc ...
```
Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.
I know how to create a custom page template for one specific page, i.e. page-*slug*.php, but I want to use one page template for all of those subpages.
What would be the easiest way to accomplish this?
|
You can always make use of the `page_template` filter to tell WordPress to use a specific page template for all child pages of a certain parent. It is as easy as creating a special page template, lets call it `page-wpse-person.php`.
Now it is as easy as including that template whenever a child page of `people` is being viewed. For the sake of example, lets say the page ID of `people` is `10`
```
add_filter( 'page_template', function ( $template ) use ( &$post )
{
// Check if we have page which is a child of people, ID 10
if ( 10 !== $post->post_parent )
return $template;
// This is a person page, child of people, try to locate our custom page
$locate_template = locate_template( 'page-wpse-person.php' );
// Check if our template was found, if not, bail
if ( !$locate_template )
return $template;
return $locate_template;
});
```
|
231,653 |
<p>I'm recoding my website with custom post types to be better organized, have a better search experience and being able to hide some pages from other contributors, but I have a little problem.</p>
<p>I've set up a post type named <em>Files</em> which contains some files that my contributors should not see. Basically the legal pages, the contact page and so on.</p>
<p>As I had all the pages in the default <em>Pages</em> post type I was able to select a template for each page in the page attributes. Now in my new custom page type, I can only select the order of the page and nothing else. So I have a template for the legal pages and another one for the contact page, which includes all the PHP code. How can I select these templates in my new custom post type?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>Okay, I've understood, that it's only possible to set a template by setting up a PHP file named <code>single-*(post_type_name)*</code>. But as I said, I've two different templates, and more will come very soon, so how can I set these to one or maybe two posts inside that post_type. There must be a possibility, isn't it? The makers of WordPress will unlikely have us create a new post_type for a single file...</p>
|
[
{
"answer_id": 231812,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 2,
"selected": true,
"text": "<p>From what I understand, you've got THREE options (updated).</p>\n<p><strong>Option 1: Dynamic Solution</strong> Create categories for your custom post type - each category is going to have its own template.</p>\n<p>You then create a single template that splits off based on category. Meaning you use the general header and footer in your single-postypename.php and anything else that you want to apply to both templates, but in the meat of it, you then create some php logic for "if category x, use content y template (or partial, I like partials)" and "if category z, use content z template (or partial)". I assume that if you're working in templates you're okay with the code for that, but if not just comment and I can put together an example.</p>\n<p><strong>Option 2: Static Solution</strong> Each post inside your custom post type gets its own template.</p>\n<p>You need the single-posttypename.php as your default, but then you can create single-postypename-postslug.php and presto, you have a custom template for that specific post that you can mess around in. As long as your slugs match, it'll just know what to do.</p>\n<p>Example:</p>\n<p>single-file.php (as your default template)</p>\n<p>single-file-legaldocument2.php (as a custom template for yourdomain.ca/file/legaldocument2 )</p>\n<p><strong>Option 3: Identify a template</strong></p>\n<p>WordPress now offers the ability to <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"nofollow noreferrer\">assign a template</a> based on post type. I don't think this can get as granular for categories of a post type or a specific post, for that you would still need solution #2.</p>\n<p>Example:</p>\n<pre><code><?php\n/*\nTemplate Name: Full-width layout\nTemplate Post Type: post, page, product\n*/\n \n</code></pre>\n"
},
{
"answer_id": 231828,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>single_template</code> filter will let you use whatever template file you want for your CPT, but it's up to you to provide some means of selection and storage of a template name or some other reference to make it a dynamic solution.</p>\n\n<p>The built-in <code>page</code> post type does this by reading all of the valid template files in your theme, and adding that list to a <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow\">meta box</a>, which stores the selected filename in post meta.</p>\n\n<p>You can quickly duplicate this behavior by saving a filename manually in a <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow\">Custom Field (post meta)</a>, then adding a filter to check for that meta key with the current post. Here's a quick untested example from my other answer linked in a comment above-</p>\n\n<pre><code>function wpa_single_cpt_template( $templates = '' ){\n $single = get_queried_object();\n\n if( 'files' == $single->post_type ){\n $template_name = get_post_meta( $single->ID, 'my_template_file', 'true' );\n if( !empty( $template_name ) ){\n $templates = locate_template( $template_name, false );\n }\n }\n return $templates;\n}\nadd_filter( 'single_template', 'wpa_single_cpt_template' );\n</code></pre>\n"
},
{
"answer_id": 264718,
"author": "Vinod Dalvi",
"author_id": 14347,
"author_profile": "https://wordpress.stackexchange.com/users/14347",
"pm_score": 1,
"selected": false,
"text": "<p>From <a href=\"https://wordpress.org/news/2016/12/vaughan/\" rel=\"nofollow noreferrer\">WordPress version 4.7</a> you can now assign custom page templates to other post types along with page. Please see the answer posted in this topic <a href=\"https://wordpress.stackexchange.com/a/264573/14347\">https://wordpress.stackexchange.com/a/264573/14347</a></p>\n"
},
{
"answer_id": 264722,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 1,
"selected": false,
"text": "<p>Create a template file like this in your child theme.</p>\n\n<pre><code><?php\n\n// Template Name: CPT Template\n// Template Post Type: files\n</code></pre>\n\n<p>Assumes files is the name of your custom post type.</p>\n\n<p>WordPress now supports <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"nofollow noreferrer\">this functionality</a></p>\n"
}
] |
2016/07/06
|
[
"https://wordpress.stackexchange.com/questions/231653",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93282/"
] |
I'm recoding my website with custom post types to be better organized, have a better search experience and being able to hide some pages from other contributors, but I have a little problem.
I've set up a post type named *Files* which contains some files that my contributors should not see. Basically the legal pages, the contact page and so on.
As I had all the pages in the default *Pages* post type I was able to select a template for each page in the page attributes. Now in my new custom page type, I can only select the order of the page and nothing else. So I have a template for the legal pages and another one for the contact page, which includes all the PHP code. How can I select these templates in my new custom post type?
---
**EDIT**
Okay, I've understood, that it's only possible to set a template by setting up a PHP file named `single-*(post_type_name)*`. But as I said, I've two different templates, and more will come very soon, so how can I set these to one or maybe two posts inside that post\_type. There must be a possibility, isn't it? The makers of WordPress will unlikely have us create a new post\_type for a single file...
|
From what I understand, you've got THREE options (updated).
**Option 1: Dynamic Solution** Create categories for your custom post type - each category is going to have its own template.
You then create a single template that splits off based on category. Meaning you use the general header and footer in your single-postypename.php and anything else that you want to apply to both templates, but in the meat of it, you then create some php logic for "if category x, use content y template (or partial, I like partials)" and "if category z, use content z template (or partial)". I assume that if you're working in templates you're okay with the code for that, but if not just comment and I can put together an example.
**Option 2: Static Solution** Each post inside your custom post type gets its own template.
You need the single-posttypename.php as your default, but then you can create single-postypename-postslug.php and presto, you have a custom template for that specific post that you can mess around in. As long as your slugs match, it'll just know what to do.
Example:
single-file.php (as your default template)
single-file-legaldocument2.php (as a custom template for yourdomain.ca/file/legaldocument2 )
**Option 3: Identify a template**
WordPress now offers the ability to [assign a template](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/) based on post type. I don't think this can get as granular for categories of a post type or a specific post, for that you would still need solution #2.
Example:
```
<?php
/*
Template Name: Full-width layout
Template Post Type: post, page, product
*/
```
|
231,685 |
<p>I was wandering... All the translation functions (<code>__(), _e(), _x()</code> and so on) use the current/active language. Is there a way to get a translation from another language than the current one? For example, I'm on a French page and I want and english translation: how to?</p>
|
[
{
"answer_id": 231888,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 2,
"selected": false,
"text": "<p>To find the answer to this question, you just need to look at how WordPress retrieves the translations. Ultimately it is the <a href=\"https://developer.wordpress.org/reference/functions/load_textdomain/#source\" rel=\"nofollow noreferrer\"><code>load_textdomain()</code></a> function that does this. When we take a look at its source we find that it creates a <code>MO</code> object and loads the translations from a <code>.mo</code> file into it. Then it stores that object in a global variable called <code>$l10n</code>, which is an array keyed by textdomain.</p>\n\n<p>To load a different locale for a particular domain, we just need to call <code>load_textdomain()</code> with the path to the <code>.mo</code> file for that locale:</p>\n\n<pre><code>$textdomain = 'your-textdomain';\n\n// First, back up the default locale, so that we don't have to reload it.\nglobal $l10n;\n\n$backup = $l10n[ $textdomain ];\n\n// Now load the .mo file for the locale that we want.\n$locale = 'en_US';\n$mo_file = $textdomain . '-' . $locale . '.mo';\n\nload_textdomain( $textdomain, $mo_file );\n\n// Translate to our heart's content!\n_e( 'Hello World!', $textdomain );\n\n// When we are done, restore the translations for the default locale.\n$l10n[ $textdomain ] = $backup;\n</code></pre>\n\n<p>To find out what logic WordPress uses to determine where to look for the <code>.mo</code> file for a plugin (like how to get the current locale), take a look at the source of <a href=\"https://developer.wordpress.org/reference/functions/load_plugin_textdomain/#source\" rel=\"nofollow noreferrer\"><code>load_plugin_textdomain()</code></a>.</p>\n"
},
{
"answer_id": 274985,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": true,
"text": "<p>So thanks to J.D., I finally ended up with this code:</p>\n\n<pre><code>function __2($string, $textdomain, $locale){\n global $l10n;\n if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain];\n load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo');\n $translation = __($string,$textdomain);\n if(isset($bkup)) $l10n[$textdomain] = $backup;\n return $translation;\n}\n\n\nfunction _e2($string, $textdomain, $locale){\n echo __2($string, $textdomain, $locale);\n}\n</code></pre>\n\n<p>Now, I know it shouldn't be, as per this famous article:</p>\n\n<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>\n\n<p>But, I don't know, it works... And bonus: say you want to use it in admin, because the admin language is x, but you want to get/save data in lang y, and you're using polylang. So i.e. your admin is english, but you're on the spanish translation of a post, and you need to get spanish data from your theme locales:</p>\n\n<pre><code>global $polylang;\n$p_locale = $polylang->curlang->locale; // will be es_ES\n_e2('your string', 'yourtextdomain', $p_locale)\n</code></pre>\n"
},
{
"answer_id": 410588,
"author": "Buzut",
"author_id": 77030,
"author_profile": "https://wordpress.stackexchange.com/users/77030",
"pm_score": 0,
"selected": false,
"text": "<p>It all really depends on your use case. I'm more adept of switching WordPress altogether as even WP localised functions such as <code>wp_date</code> will work as expected.</p>\n<p>For instance, let's say you need translated content in a cron job depending on the user locale, you can programmatically switch WP locale.</p>\n<pre><code>// Get user locale if needed\n$user_locale = get_user_locale($user_id);\n\n// Now change WP locale if needed\nif ($user_locale !== get_locale()) switch_to_locale($user_locale);\n</code></pre>\n<p>After that, all core functions will be localised and calls to any of the translation functions (<code>__()</code>, <code>_e()</code>, <code>_x()</code>) will be in the required locale.</p>\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale</code></a> function was added in WP 4.7. Nothing prevents you from switching in back afterwards.</p>\n"
}
] |
2016/07/07
|
[
"https://wordpress.stackexchange.com/questions/231685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] |
I was wandering... All the translation functions (`__(), _e(), _x()` and so on) use the current/active language. Is there a way to get a translation from another language than the current one? For example, I'm on a French page and I want and english translation: how to?
|
So thanks to J.D., I finally ended up with this 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;
}
function _e2($string, $textdomain, $locale){
echo __2($string, $textdomain, $locale);
}
```
Now, I know it shouldn't be, as per this famous article:
<http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/>
But, I don't know, it works... And bonus: say you want to use it in admin, because the admin language is x, but you want to get/save data in lang y, and you're using polylang. So i.e. your admin is english, but you're on the spanish translation of a post, and you need to get spanish data from your theme locales:
```
global $polylang;
$p_locale = $polylang->curlang->locale; // will be es_ES
_e2('your string', 'yourtextdomain', $p_locale)
```
|
231,693 |
<p>I am developing a theme with Underscores for WordPress. </p>
<p>When the user adds an image using the TinyMCE editor the following code is inserted: </p>
<pre><code><img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" />
</code></pre>
<p>When I look at the final page generated by Wordpress, the HTML appears in the DOM</p>
<pre><code><img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" srcset="http://example.com/wp-content/uploads/2016/06/process.png 849w, http://example.com/wp-content/uploads/2016/06/process-300x32.png 300w, http://example.com/wp-content/uploads/2016/06/process-768x82.png 768w" sizes="(max-width: 849px) 100vw, 849px">
</code></pre>
<p>I have created a function to generate a thumbnail with a width of 300px: </p>
<pre><code>add_action( 'after_setup_theme', 'images_theme_setup' );
function images_theme_setup() {
add_image_size( 'preload-thumb', 300 ); // 300 pixels wide (and unlimited height)
}
</code></pre>
<p>Now I want to use Pil (<a href="https://github.com/gilbitron/Pil" rel="nofollow">https://github.com/gilbitron/Pil</a>) compatible markup to serve images so I can serve the <code>preload-thumb</code> and then serve the larger image</p>
<p>I need to change to the markup to match this below </p>
<pre><code><figure class="pil">
<img src="img/my-image.jpg" data-pil-thumb-url="img/thumb-my-image.jpg" data-full-width="5616" data-full-height="3744" alt="">
</figure>
</code></pre>
|
[
{
"answer_id": 231695,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>There's a filter called <a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"nofollow\"><code>image_send_to_editor</code></a> that lets you specify the markup. You will also need <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata\" rel=\"nofollow\"><code>wp_get_attachment_metadata</code></a> to retrieve width and height. It is called like this (untested):</p>\n\n<pre><code> add_filter( 'image_send_to_editor', 'wpse_231693_img_markup', 10, 7 );\n function wpse_231693_img_markup ($html, $id, $alt, $title, $align, $url, $size ) {\n $metadata = wp_get_attachment_metadata ($id);\n $url = wp_get_attachment_url($id);\n $html = '<figure class=\"pil\"><img src=\"' . $url . \n '\" data-pil-thumb-url=\"XXX\" data-full-width=\"' . $metadata['width'] .\n '\" data-full-height=\"' . $metadata['height'] .\n '\" alt=\"' . $alt . '\"></figure>';\n return $html;\n }\n</code></pre>\n\n<p>You will need some clever regex to construct XXX from $url, but I'll leave that to you.</p>\n"
},
{
"answer_id": 231697,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 4,
"selected": true,
"text": "<p>As far as I know you could hook into the filter <a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"nofollow\"><code>image_send_to_editor</code></a> like this: </p>\n\n<pre><code>function html5_insert_image($html, $id, $caption, $title, $align, $url) {\n $url = wp_get_attachment_url($id);\n $html5 = \"<figure id='post-$id media-$id' class='align-$align'>\";\n $html5 .= \"<img src='$url' alt='$title' />\";\n $html5 .= \"</figure>\";\n return $html5;\n}\nadd_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );\n</code></pre>\n\n<p>For additional tags like <code>data-pil-thumb-url</code> and <code>data-full-width</code> and <code>data-full-height</code>you could add the appropriate code inside that function and add them to the <code>$html5</code> string. </p>\n\n<p>See also <a href=\"https://css-tricks.com/snippets/wordpress/insert-images-within-figure-element-from-media-uploader/\" rel=\"nofollow\">this page</a> for an example featuring a caption <code><figcaption></code> at css-tricks or check <a href=\"http://synapticism.com/dev/experimenting-with-html5-image-markup-and-shortcodes-in-wordpress/\" rel=\"nofollow\">this</a> more detailed 'walk through'.</p>\n"
}
] |
2016/07/07
|
[
"https://wordpress.stackexchange.com/questions/231693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82713/"
] |
I am developing a theme with Underscores for WordPress.
When the user adds an image using the TinyMCE editor the following code is inserted:
```
<img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" />
```
When I look at the final page generated by Wordpress, the HTML appears in the DOM
```
<img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" srcset="http://example.com/wp-content/uploads/2016/06/process.png 849w, http://example.com/wp-content/uploads/2016/06/process-300x32.png 300w, http://example.com/wp-content/uploads/2016/06/process-768x82.png 768w" sizes="(max-width: 849px) 100vw, 849px">
```
I have created a function to generate a thumbnail with a width of 300px:
```
add_action( 'after_setup_theme', 'images_theme_setup' );
function images_theme_setup() {
add_image_size( 'preload-thumb', 300 ); // 300 pixels wide (and unlimited height)
}
```
Now I want to use Pil (<https://github.com/gilbitron/Pil>) compatible markup to serve images so I can serve the `preload-thumb` and then serve the larger image
I need to change to the markup to match this below
```
<figure class="pil">
<img src="img/my-image.jpg" data-pil-thumb-url="img/thumb-my-image.jpg" data-full-width="5616" data-full-height="3744" alt="">
</figure>
```
|
As far as I know you could hook into the filter [`image_send_to_editor`](https://developer.wordpress.org/reference/hooks/image_send_to_editor/) like this:
```
function html5_insert_image($html, $id, $caption, $title, $align, $url) {
$url = wp_get_attachment_url($id);
$html5 = "<figure id='post-$id media-$id' class='align-$align'>";
$html5 .= "<img src='$url' alt='$title' />";
$html5 .= "</figure>";
return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );
```
For additional tags like `data-pil-thumb-url` and `data-full-width` and `data-full-height`you could add the appropriate code inside that function and add them to the `$html5` string.
See also [this page](https://css-tricks.com/snippets/wordpress/insert-images-within-figure-element-from-media-uploader/) for an example featuring a caption `<figcaption>` at css-tricks or check [this](http://synapticism.com/dev/experimenting-with-html5-image-markup-and-shortcodes-in-wordpress/) more detailed 'walk through'.
|
231,711 |
<p>I have six regular categories, not custom (each category having between 5 and 10 posts) and I am trying to display one random post from each category on the page. </p>
<p>The problem with the output is getting the random posts is fine, but some posts are taken from the same category which I do not want. Here is the code I am using it:</p>
<pre><code>$args_ = array(
'posts_per_page' => 6,
'orderby' => 'rand',
'exclude' => $postid , // the current post ID
'category' => $cat_id_array // here is the array of categories
);
$myposts = get_posts( $args_ );
//var_dump($myposts); // I have duplicate category here
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endforeach;
wp_reset_postdata();
</code></pre>
<p>Any help would be appreciated. </p>
|
[
{
"answer_id": 231715,
"author": "cadobe",
"author_id": 58295,
"author_profile": "https://wordpress.stackexchange.com/users/58295",
"pm_score": 1,
"selected": false,
"text": "<p>I just fix it using bueltge sugestion such us:</p>\n\n<pre><code>foreach ( $cat_id_array as $cat ) :\n\n $args = array( 'posts_per_page' => 1, 'cat' => $cat );\n $myposts = get_posts( $args );\n //var_dump($myposts);\n\n foreach($myposts as $posts) :\n var_dump($posts->ID);\n\n endforeach;\nendforeach;\n</code></pre>\n\n<p>which is working fine now. Thanks for the heads up. DO I have any chance to reduce the queries number for this particular code? It is showing as 30 queries</p>\n"
},
{
"answer_id": 231756,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Random ordering is quite expensive operations in SQL and can become a headache on very big sites. Getting a random post from a category for 6 categories will mean you might need to run 6 separate queries, each ordered randomly. This can really break the bank and leave you bankrupt. </p>\n\n<p>From your answer and looking at the fact that you said you are running 30 queries, this is quite evident. Also, what really makes this expensive is that post thumbnails aren't cached for custom queries, so you are making a db call everytime you query a post thumbnail.</p>\n\n<p>Lets trey a different approach, and if we are clever, we can reduce your queries to almost nothing. This is what we will do</p>\n\n<ul>\n<li><p>Query all the posts from the db. It is here where we need to be clever as this is an extremely expensive operation. The only thing that we really need from the posts is their ID's, so we will only query the post ID's, and that will drastically reduce db queries and time spend to run the query</p></li>\n<li><p>Once we have all the post ID's, we will sort them according to categories</p></li>\n<li><p>We will then pick 6 random ids from the sorted array, one per category, and this will be passed to our \"main\" query which will output the posts.</p></li>\n</ul>\n\n<p>The first two operations will only require 2 or three queries, this you can verify with a plugin like <em>Query Monitor</em></p>\n\n<p>Lets look at some code: (<em>NOTE: All code is untested and requires PHP 5.4+</em>)</p>\n\n<h2>THE QUERY</h2>\n\n<pre><code>// Lets get all the post ids\n$args = [\n 'posts_per_page' => -1,\n 'fields' => 'ids' // Only get the post ID's\n];\n$ids_array = get_posts( $args );\n\n// Make sure we have a valid array of ids\nif ( $ids_array ) {\n // Lets update the post term cache\n update_object_term_cache( $ids_array, 'post' );\n\n // Loop through the post ids and create an array with post ids and terms\n $id_and_term_array = [];\n foreach ( $ids_array as $id ) {\n // Get all the post categories\n $terms = get_the_terms( $id, 'category' );\n\n // Make sure we have a valid array of terms\n if ( $terms\n && !is_wp_error( $terms )\n ) {\n // Loop through the terms and create our array with post ids and term\n foreach ( $terms as $term )\n $id_and_term_array[$term->term_id][] = $id;\n }\n }\n\n // TO BE CONTINUED......\n}\n</code></pre>\n\n<p>Great, <code>$id_and_term_array</code> should now contain an array with arrays where the keys are term ids and the values are an array of post ids. We have created all of this without breaking the bank. If you check query monitor, you will see all of this required only 2 db calls in about no time. We have slightly abused memory, but we will later look at something to avoid eating up memory.</p>\n\n<h2>SELECTING RANDOM ID'S</h2>\n\n<p>What we will do next is to loop through <code>$id_and_term_array</code> and pick a random post id from each term id array. We also need to exclude the current post id and need to avoid duplicate post id's which we will certainly have if posts belongs to more than one term. </p>\n\n<p>So lets continue where we last placed <em>TO BE CONTINUED....</em></p>\n\n<pre><code>// Make sure we have a valid array\nif ( $id_and_term_array ) {\n // Get the current post ID\n $current_post_id = get_the_ID();\n // If this is a single post page, we can do\n // $current_post_id = $GLOBALS['wp_the_query']->get_queried_object_id();\n\n // Lets loop through $id_and_term_array\n $unique_rand_array = [];\n foreach ( $id_and_term_array as $value ) {\n // Shuffle the $value array to randomize it\n shuffle ( $value );\n\n // Loop through $value and get the first post id\n foreach ( $value as $v ) {\n // Skip the post ID if it mathes the current post or if it is a duplicate\n if ( $v == $current_post_id )\n continue;\n\n if ( in_array( $v, $unique_rand_array ) )\n continue;\n\n // We have a unique id, lets store it and bail\n $unique_rand_array[] = $v;\n\n break;\n }\n }\n}\n</code></pre>\n\n<p>We now have an array with x amount of unique post id's which is stored in <code>$unique_rand_array</code>. We can now pass that array of id's to our final query</p>\n\n<h2>FINAL QUERY</h2>\n\n<pre><code>// First see if we have post ids in array\nif ( $unique_rand_array ) {\n // Lets run our query\n $final_args = [\n 'posts_per_page' => 6,\n 'post__in' => shuffle( $unique_rand_array ), // Randomize posts\n 'orderby' => 'post__in' // Keep post order the same as the order of post ids\n ];\n $q = new WP_Query( $final_args );\n\n // Lets cache our post thumbnails\n update_post_thumbnail_cache( $q );\n\n while ( $q->have_posts() ) :\n $q->the_post();\n\n ?>\n <div class=\"col-md-4\">\n <?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </div>\n <?php\n\n endwhile;\n wp_reset_postdata();\n}\n</code></pre>\n\n<h2>TRANSIENTS</h2>\n\n<p>One last thing we can do is to savethe results for our first query in transient because we do not want to run that query on every page load. This will reduce memory abuse and avoid. We will also delete our transient when we publish a new post</p>\n\n<h1>ALL TOGETHER NOW</h1>\n\n<p>Let put everything together. </p>\n\n<pre><code>// Check if we have a transient\nif ( false === ( $id_and_term_array = get_transient( 'random_term_post_ids' ) ) ) {\n\n // Lets get all the post ids\n $args = [\n 'posts_per_page' => -1,\n 'fields' => 'ids' // Only get the post ID's\n ];\n $ids_array = get_posts( $args );\n\n // Define the array which will hold the term and post_ids\n $id_and_term_array = [];\n // Make sure we have a valid array of ids\n if ( $ids_array ) {\n // Lets update the post term cache\n update_object_term_cache( $ids_array, 'post' );\n\n // Loop through the post ids and create an array with post ids and terms\n foreach ( $ids_array as $id ) {\n // Get all the post categories\n $terms = get_the_terms( $id, 'category' );\n\n // Make sure we have a valid array of terms\n if ( $terms\n && !is_wp_error( $terms )\n ) {\n // Loop through the terms and create our array with post ids and term\n foreach ( $terms as $term )\n $id_and_term_array[$term->term_id][] = $id;\n }\n }\n }\n // Set our transient for 30 days\n set_transient( 'random_term_post_ids', $id_and_term_array, 30 * DAYS_IN_SECONDS );\n}\n\n// Make sure we have a valid array\nif ( $id_and_term_array ) {\n // Get the current post ID\n $current_post_id = get_the_ID();\n // If this is a single post page, we can do\n // $current_post_id = $GLOBALS['wp_the_query']->get_queried_object_id();\n\n // Lets loop through $id_and_term_array\n $unique_rand_array = [];\n foreach ( $id_and_term_array as $value ) {\n // Shuffle the $value array to randomize it\n shuffle ( $value );\n\n // Loop through $value and get the first post id\n foreach ( $value as $v ) {\n // Skip the post ID if it mathes the current post or if it is a duplicate\n if ( $v == $current_post_id )\n continue;\n\n if ( in_array( $v, $unique_rand_array ) )\n continue;\n\n // We have a unique id, lets store it and bail\n $unique_rand_array[] = $v;\n\n break;\n }\n }\n\n // First see if we have post ids in array\n if ( $unique_rand_array ) {\n // Lets run our query\n $final_args = [\n 'posts_per_page' => 6,\n 'post__in' => shuffle( $unique_rand_array ), // Randomize posts\n 'orderby' => 'post__in' // Keep post order the same as the order of post ids\n ];\n $q = new WP_Query( $final_args );\n\n // Lets cache our post thumbnails\n update_post_thumbnail_cache( $q );\n\n while ( $q->have_posts() ) :\n $q->the_post();\n\n ?>\n <div class=\"col-md-4\">\n <?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </div>\n <?php\n\n endwhile;\n wp_reset_postdata();\n }\n}\n</code></pre>\n\n<p>Finally, the following code goes into your functions file. This will flush the transient when a new post is published, a post is deleted, updated or undeleted</p>\n\n<pre><code>add_action( 'transition_post_status', function () \n{\n delete_transient( 'random_term_post_ids' );\n});\n</code></pre>\n"
}
] |
2016/07/07
|
[
"https://wordpress.stackexchange.com/questions/231711",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58295/"
] |
I have six regular categories, not custom (each category having between 5 and 10 posts) and I am trying to display one random post from each category on the page.
The problem with the output is getting the random posts is fine, but some posts are taken from the same category which I do not want. Here is the code I am using it:
```
$args_ = array(
'posts_per_page' => 6,
'orderby' => 'rand',
'exclude' => $postid , // the current post ID
'category' => $cat_id_array // here is the array of categories
);
$myposts = get_posts( $args_ );
//var_dump($myposts); // I have duplicate category here
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endforeach;
wp_reset_postdata();
```
Any help would be appreciated.
|
Random ordering is quite expensive operations in SQL and can become a headache on very big sites. Getting a random post from a category for 6 categories will mean you might need to run 6 separate queries, each ordered randomly. This can really break the bank and leave you bankrupt.
From your answer and looking at the fact that you said you are running 30 queries, this is quite evident. Also, what really makes this expensive is that post thumbnails aren't cached for custom queries, so you are making a db call everytime you query a post thumbnail.
Lets trey a different approach, and if we are clever, we can reduce your queries to almost nothing. This is what we will do
* Query all the posts from the db. It is here where we need to be clever as this is an extremely expensive operation. The only thing that we really need from the posts is their ID's, so we will only query the post ID's, and that will drastically reduce db queries and time spend to run the query
* Once we have all the post ID's, we will sort them according to categories
* We will then pick 6 random ids from the sorted array, one per category, and this will be passed to our "main" query which will output the posts.
The first two operations will only require 2 or three queries, this you can verify with a plugin like *Query Monitor*
Lets look at some code: (*NOTE: All code is untested and requires PHP 5.4+*)
THE QUERY
---------
```
// Lets get all the post ids
$args = [
'posts_per_page' => -1,
'fields' => 'ids' // Only get the post ID's
];
$ids_array = get_posts( $args );
// Make sure we have a valid array of ids
if ( $ids_array ) {
// Lets update the post term cache
update_object_term_cache( $ids_array, 'post' );
// Loop through the post ids and create an array with post ids and terms
$id_and_term_array = [];
foreach ( $ids_array as $id ) {
// Get all the post categories
$terms = get_the_terms( $id, 'category' );
// Make sure we have a valid array of terms
if ( $terms
&& !is_wp_error( $terms )
) {
// Loop through the terms and create our array with post ids and term
foreach ( $terms as $term )
$id_and_term_array[$term->term_id][] = $id;
}
}
// TO BE CONTINUED......
}
```
Great, `$id_and_term_array` should now contain an array with arrays where the keys are term ids and the values are an array of post ids. We have created all of this without breaking the bank. If you check query monitor, you will see all of this required only 2 db calls in about no time. We have slightly abused memory, but we will later look at something to avoid eating up memory.
SELECTING RANDOM ID'S
---------------------
What we will do next is to loop through `$id_and_term_array` and pick a random post id from each term id array. We also need to exclude the current post id and need to avoid duplicate post id's which we will certainly have if posts belongs to more than one term.
So lets continue where we last placed *TO BE CONTINUED....*
```
// Make sure we have a valid array
if ( $id_and_term_array ) {
// Get the current post ID
$current_post_id = get_the_ID();
// If this is a single post page, we can do
// $current_post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
// Lets loop through $id_and_term_array
$unique_rand_array = [];
foreach ( $id_and_term_array as $value ) {
// Shuffle the $value array to randomize it
shuffle ( $value );
// Loop through $value and get the first post id
foreach ( $value as $v ) {
// Skip the post ID if it mathes the current post or if it is a duplicate
if ( $v == $current_post_id )
continue;
if ( in_array( $v, $unique_rand_array ) )
continue;
// We have a unique id, lets store it and bail
$unique_rand_array[] = $v;
break;
}
}
}
```
We now have an array with x amount of unique post id's which is stored in `$unique_rand_array`. We can now pass that array of id's to our final query
FINAL QUERY
-----------
```
// First see if we have post ids in array
if ( $unique_rand_array ) {
// Lets run our query
$final_args = [
'posts_per_page' => 6,
'post__in' => shuffle( $unique_rand_array ), // Randomize posts
'orderby' => 'post__in' // Keep post order the same as the order of post ids
];
$q = new WP_Query( $final_args );
// Lets cache our post thumbnails
update_post_thumbnail_cache( $q );
while ( $q->have_posts() ) :
$q->the_post();
?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php
endwhile;
wp_reset_postdata();
}
```
TRANSIENTS
----------
One last thing we can do is to savethe results for our first query in transient because we do not want to run that query on every page load. This will reduce memory abuse and avoid. We will also delete our transient when we publish a new post
ALL TOGETHER NOW
================
Let put everything together.
```
// Check if we have a transient
if ( false === ( $id_and_term_array = get_transient( 'random_term_post_ids' ) ) ) {
// Lets get all the post ids
$args = [
'posts_per_page' => -1,
'fields' => 'ids' // Only get the post ID's
];
$ids_array = get_posts( $args );
// Define the array which will hold the term and post_ids
$id_and_term_array = [];
// Make sure we have a valid array of ids
if ( $ids_array ) {
// Lets update the post term cache
update_object_term_cache( $ids_array, 'post' );
// Loop through the post ids and create an array with post ids and terms
foreach ( $ids_array as $id ) {
// Get all the post categories
$terms = get_the_terms( $id, 'category' );
// Make sure we have a valid array of terms
if ( $terms
&& !is_wp_error( $terms )
) {
// Loop through the terms and create our array with post ids and term
foreach ( $terms as $term )
$id_and_term_array[$term->term_id][] = $id;
}
}
}
// Set our transient for 30 days
set_transient( 'random_term_post_ids', $id_and_term_array, 30 * DAYS_IN_SECONDS );
}
// Make sure we have a valid array
if ( $id_and_term_array ) {
// Get the current post ID
$current_post_id = get_the_ID();
// If this is a single post page, we can do
// $current_post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
// Lets loop through $id_and_term_array
$unique_rand_array = [];
foreach ( $id_and_term_array as $value ) {
// Shuffle the $value array to randomize it
shuffle ( $value );
// Loop through $value and get the first post id
foreach ( $value as $v ) {
// Skip the post ID if it mathes the current post or if it is a duplicate
if ( $v == $current_post_id )
continue;
if ( in_array( $v, $unique_rand_array ) )
continue;
// We have a unique id, lets store it and bail
$unique_rand_array[] = $v;
break;
}
}
// First see if we have post ids in array
if ( $unique_rand_array ) {
// Lets run our query
$final_args = [
'posts_per_page' => 6,
'post__in' => shuffle( $unique_rand_array ), // Randomize posts
'orderby' => 'post__in' // Keep post order the same as the order of post ids
];
$q = new WP_Query( $final_args );
// Lets cache our post thumbnails
update_post_thumbnail_cache( $q );
while ( $q->have_posts() ) :
$q->the_post();
?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php
endwhile;
wp_reset_postdata();
}
}
```
Finally, the following code goes into your functions file. This will flush the transient when a new post is published, a post is deleted, updated or undeleted
```
add_action( 'transition_post_status', function ()
{
delete_transient( 'random_term_post_ids' );
});
```
|
231,815 |
<p>Is there a way to remove styles added with wp_add_inline_style?</p>
<p>I noticed if I call wp_add_inline_style multiple times, it just keeps adding style, it does not overwrite what was added before.</p>
<p>The plugin is adding styles:</p>
<pre><code>$inline_css = '#selector{
color:red;
}';
wp_add_inline_style($style, $inline_css);
</code></pre>
<p>If I do this again:</p>
<pre><code>$inline_css = '#other-selector{
color:blue;
}';
wp_add_inline_style($style, $inline_css);
</code></pre>
<p>It will just append those css, I would like to clear css before calling wp_add_inline_style again. </p>
|
[
{
"answer_id": 231820,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>Looking into <code>wp-includes/class.wp-styles.php</code> core file I found a filter to use:</p>\n\n<pre><code>add_action(\"print_styles_array\", function( $styles ) { \n $my_handle = \"custom-style\"; // your custom handle here, the one declared as $style in question\n if ( !empty( $styles ) ) {\n foreach ( $styles as $i => $style ) {\n if ( $my_handle === $style ) {\n unset( $styles[$i] );\n }\n }\n }\n return $styles;\n});\n</code></pre>\n\n<p>Note that this will remove all inline styles processed by the handle name.</p>\n"
},
{
"answer_id": 231821,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<h2>Remove styles added with <code>wp_add_inline_style()</code></h2>\n<p>If we want to keep the <code>custom-style-css</code> but only remove the <code>custom-style-inline-css</code>, then we can try e.g.</p>\n<pre><code>add_action( 'wp_print_styles', function()\n{\n // Remove previous inline style\n wp_styles()->add_data( 'custom-style', 'after', '' ); \n\n} );\n</code></pre>\n<p>where <code>after</code> is data key for the inline style corresponding to the <code>custom-style</code> handler.</p>\n<p>There is exists a wrapper for <code>wp_styles()->add_data()</code>, namely <a href=\"https://developer.wordpress.org/reference/functions/wp_style_add_data/\" rel=\"nofollow noreferrer\"><code>wp_style_add_data()</code></a>.</p>\n<p>We could then define the helper function:</p>\n<pre><code>function wpse_remove_inline_style( $handler )\n{\n wp_style_is( $handler, 'enqueued' ) \n && wp_style_add_data( $handler, 'after', '' );\n}\n</code></pre>\n<p>and use it like:</p>\n<pre><code>add_action( 'wp_print_styles', function()\n{\n // Remove previous inline style\n wpse_remove_inline_style( 'custom-style' ); \n\n} );\n</code></pre>\n<p>I'm skipping the <code>function_exists</code> check here.</p>\n<p>To override the inline-style, added by another plugin, with our own:</p>\n<pre><code>add_action( 'wp_print_styles', function()\n{\n // Remove previous inline style\n wpse_remove_inline_style( 'custom-style' ); \n\n // New inline style\n $custom_css = ".mycolor{\n background: {blue};\n }";\n wp_add_inline_style( 'custom-style', $custom_css );\n\n} );\n</code></pre>\n<h2>Note</h2>\n<p>The reason why it doesn't work to override previous inline style with <code>wp_add_inline_style()</code> is because the <code>WP_Style::add_inline_style()</code> appends each incoming CSS string into an array. Internally it uses <code>WP_Style::add_data()</code> to store the accumulated CSS. Here we are using it to overcome the <em>appending</em> restriction of <code>wp_add_inline_style()</code>.</p>\n"
}
] |
2016/07/08
|
[
"https://wordpress.stackexchange.com/questions/231815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45321/"
] |
Is there a way to remove styles added with wp\_add\_inline\_style?
I noticed if I call wp\_add\_inline\_style multiple times, it just keeps adding style, it does not overwrite what was added before.
The plugin is adding styles:
```
$inline_css = '#selector{
color:red;
}';
wp_add_inline_style($style, $inline_css);
```
If I do this again:
```
$inline_css = '#other-selector{
color:blue;
}';
wp_add_inline_style($style, $inline_css);
```
It will just append those css, I would like to clear css before calling wp\_add\_inline\_style again.
|
Remove styles added with `wp_add_inline_style()`
------------------------------------------------
If we want to keep the `custom-style-css` but only remove the `custom-style-inline-css`, then we can try e.g.
```
add_action( 'wp_print_styles', function()
{
// Remove previous inline style
wp_styles()->add_data( 'custom-style', 'after', '' );
} );
```
where `after` is data key for the inline style corresponding to the `custom-style` handler.
There is exists a wrapper for `wp_styles()->add_data()`, namely [`wp_style_add_data()`](https://developer.wordpress.org/reference/functions/wp_style_add_data/).
We could then define the helper function:
```
function wpse_remove_inline_style( $handler )
{
wp_style_is( $handler, 'enqueued' )
&& wp_style_add_data( $handler, 'after', '' );
}
```
and use it like:
```
add_action( 'wp_print_styles', function()
{
// Remove previous inline style
wpse_remove_inline_style( 'custom-style' );
} );
```
I'm skipping the `function_exists` check here.
To override the inline-style, added by another plugin, with our own:
```
add_action( 'wp_print_styles', function()
{
// Remove previous inline style
wpse_remove_inline_style( 'custom-style' );
// New inline style
$custom_css = ".mycolor{
background: {blue};
}";
wp_add_inline_style( 'custom-style', $custom_css );
} );
```
Note
----
The reason why it doesn't work to override previous inline style with `wp_add_inline_style()` is because the `WP_Style::add_inline_style()` appends each incoming CSS string into an array. Internally it uses `WP_Style::add_data()` to store the accumulated CSS. Here we are using it to overcome the *appending* restriction of `wp_add_inline_style()`.
|
231,816 |
<p>I have created a simple plugin that locks down content for users not logged in and it is working fine. However any user on a multi-author site could use the same short code in his post to lock down content too. I do not want this to happen. </p>
<p>How may I restrict this functionality to administrators only?
This current code thows up a fatal error:Fatal error: Call to undefined function wp_get_current_user()</p>
<pre><code>public function check_user_role() {
if(current_user_can( 'activate_plugins' )) {
return true;
}
}
</code></pre>
<p>I then intended to use this method in my class constructor to determine if the add_shortcode() function should run. Any clues how I should go about implementing this shall be appreciated.</p>
|
[
{
"answer_id": 231818,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Fatal error: Call to undefined function wp_get_current_user()</p>\n</blockquote>\n\n<p>This can be fixed by declaring <code>check_user_role</code> only when WP is ready, hooking into <code>wp</code> (to use WordPress functions and methods) or performing other workaround.</p>\n\n<p>Simply check if <code>manage_options</code> capability is there for the user too ( or verify if administrator is in the roles list <code>in_array( \"administrator\", $current_user->roles )</code> ):</p>\n\n<pre><code>add_action(\"wp\", function() { \n function check_user_role() {\n return current_user_can( \"manage_options\" ) && current_user_can( 'activate_plugins' );\n }\n});\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 232443,
"author": "Terungwa",
"author_id": 96667,
"author_profile": "https://wordpress.stackexchange.com/users/96667",
"pm_score": -1,
"selected": false,
"text": "<p>To restrict the use of the shortcode on posts created by administrators only, I need to check if the post author of the post viewed is an administrator as shown in code <code>if ( user_can( $post->post_author, 'activate_plugins' ) )</code>. IF not, the content is returned without executing the <code>do_shortcode($content)</code> function.</p>\n\n<p>The <code>current_user_can()</code> function is not appropriate as it checks the current user and not the post author.</p>\n\n<pre><code>public function check_login($atts, $content = null)\n{ \n if (is_user_logged_in() && !is_null($content) && !is_feed())\n { \n return do_shortcode($content); \n }\n else\n {\n global $post; \n if ($post instanceof \\WP_Post) {\n if ( user_can( $post->post_author, 'activate_plugins' ) ) {\n return '<p>You must be logged in to view this post..</p>'; \n }\n return $content; \n } \n }\n}\n</code></pre>\n\n<p>I hope this helps someone else.</p>\n"
}
] |
2016/07/08
|
[
"https://wordpress.stackexchange.com/questions/231816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96667/"
] |
I have created a simple plugin that locks down content for users not logged in and it is working fine. However any user on a multi-author site could use the same short code in his post to lock down content too. I do not want this to happen.
How may I restrict this functionality to administrators only?
This current code thows up a fatal error:Fatal error: Call to undefined function wp\_get\_current\_user()
```
public function check_user_role() {
if(current_user_can( 'activate_plugins' )) {
return true;
}
}
```
I then intended to use this method in my class constructor to determine if the add\_shortcode() function should run. Any clues how I should go about implementing this shall be appreciated.
|
>
> Fatal error: Call to undefined function wp\_get\_current\_user()
>
>
>
This can be fixed by declaring `check_user_role` only when WP is ready, hooking into `wp` (to use WordPress functions and methods) or performing other workaround.
Simply check if `manage_options` capability is there for the user too ( or verify if administrator is in the roles list `in_array( "administrator", $current_user->roles )` ):
```
add_action("wp", function() {
function check_user_role() {
return current_user_can( "manage_options" ) && current_user_can( 'activate_plugins' );
}
});
```
Hope that helps.
|
231,838 |
<p>I have created custom page template. Now I have to make it configurable, however since I am using more than one template in my theme I would like to make sure that configuration will be available only when the user chooses this template for a page. Is there an option to do so? </p>
<p><code>add_meta_box</code> accepts different <code>$post_type</code>, so the closest I can get is to add metabox to all pages, which I would like to avoid. </p>
|
[
{
"answer_id": 231839,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>\"<em>available only when user choose this template</em>\" ? I'm not sure (I doubt it) if this is even possible. Instead I would suggest either of the following two options: </p>\n\n<p>If you want to make the page template configurable on a per-page basis then meta boxes could be the right direction. You could for example add an option like \"use featured image as background\" or the like…</p>\n\n<p>If however you would like to make your page template configurable on a more general basis, you could use Theme Options instead. Here's an introduction in the codex: <a href=\"https://codex.wordpress.org/Creating_Options_Pages\" rel=\"nofollow\">https://codex.wordpress.org/Creating_Options_Pages</a></p>\n"
},
{
"answer_id": 231845,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": true,
"text": "<pre><code><?\n// Check:\n// 1. If you are editing post, CPT, or page\n// 2. If post type IS NOT SET\nif( 'post.php' == basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']) && !isset($_GET['post_type']) ) {\n\n // get post ID\n $postid = $_GET['post']; \n\n // check the template file name\n if ('my_template.php' == get_page_template_slug($postid) ) {\n // add your metabox here\n add_action( 'add_meta_boxes', 'my_metabox' );\n }\n\n}\n</code></pre>\n\n<p>I don't remember why I was checking post type, not post ID, but you can change</p>\n\n<pre><code>!isset($_GET['post_type'])\n</code></pre>\n\n<p>to check if post ID is set:</p>\n\n<pre><code>isset($_GET['post'])\n</code></pre>\n\n<p><strong>Note</strong>: meta box will be available only after you save your post (page) using appropriate template.</p>\n"
}
] |
2016/07/09
|
[
"https://wordpress.stackexchange.com/questions/231838",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77480/"
] |
I have created custom page template. Now I have to make it configurable, however since I am using more than one template in my theme I would like to make sure that configuration will be available only when the user chooses this template for a page. Is there an option to do so?
`add_meta_box` accepts different `$post_type`, so the closest I can get is to add metabox to all pages, which I would like to avoid.
|
```
<?
// Check:
// 1. If you are editing post, CPT, or page
// 2. If post type IS NOT SET
if( 'post.php' == basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']) && !isset($_GET['post_type']) ) {
// get post ID
$postid = $_GET['post'];
// check the template file name
if ('my_template.php' == get_page_template_slug($postid) ) {
// add your metabox here
add_action( 'add_meta_boxes', 'my_metabox' );
}
}
```
I don't remember why I was checking post type, not post ID, but you can change
```
!isset($_GET['post_type'])
```
to check if post ID is set:
```
isset($_GET['post'])
```
**Note**: meta box will be available only after you save your post (page) using appropriate template.
|
231,862 |
<p>I am adding a function to the header:</p>
<pre><code>add_action('wp_head', 'mine');
function mine() {
global $authordata;
$avatar_url = get_avatar_ur($authordata->user_email);
// ....
}
</code></pre>
<p>But I am getting the error: <code>trying to get property of non-object</code>.
I guess this is because I am in the header and not inside the post.</p>
<p>How can I access the authordata data from the header, and only when in a post page?</p>
|
[
{
"answer_id": 231876,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p>The global <code>$authordata</code> variable is only available by default when <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583\" rel=\"nofollow\"><code>$wp_query->is_author() && isset($wp_query->post)</code> condition</a> is satisfied.</p>\n\n<p>It means that you can't access <code>$authordata</code> inside a single post page.</p>\n\n<p>You may try to get author data via <code>$wp_query</code>:</p>\n\n<pre><code>add_action('wp_head', function()\n{\n global $wp_query;\n\n $userdata = get_userdata($wp_query->post->post_author);\n $avatar_url = get_avatar_ur($userdata->user_email);\n ...\n}, 10, 0);\n</code></pre>\n"
},
{
"answer_id": 231894,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>Since the paste has worked perfect for you, let me turn it into an answer.</p>\n\n<p>You can always get the author of a given post with certain methods, let's use <code>get_post_field( 'post_author', $post_id )</code> for this.</p>\n\n<p>To get the data of a given user, there's <a href=\"https://developer.wordpress.org/reference/functions/get_userdata/\" rel=\"nofollow\"><code>get_userdata()</code></a> function to use. We'll pass the author ID as first param to this function to get the author data outside the loop and where the post data are set:</p>\n\n<pre><code>add_action('wp_head', 'mine');\nfunction mine() {\n if ( !is_single() )\n return; // this is not a single post\n\n if ( empty( ( $author = (int) get_post_field( 'post_author', get_the_ID() ) ) ) )\n return; // no author was caught\n\n $authordata = get_userdata( $author );\n\n $avatar_url = get_avatar_url($authordata->user_email);\n // ....\n}\n</code></pre>\n\n<p>This will always work as long as the single post' type is <code>post</code>. To expand to pages, call <code>is_page()</code>, or to custom post types <code>is_singular()</code></p>\n"
}
] |
2016/07/09
|
[
"https://wordpress.stackexchange.com/questions/231862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98079/"
] |
I am adding a function to the header:
```
add_action('wp_head', 'mine');
function mine() {
global $authordata;
$avatar_url = get_avatar_ur($authordata->user_email);
// ....
}
```
But I am getting the error: `trying to get property of non-object`.
I guess this is because I am in the header and not inside the post.
How can I access the authordata data from the header, and only when in a post page?
|
The global `$authordata` variable is only available by default when [`$wp_query->is_author() && isset($wp_query->post)` condition](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583) is satisfied.
It means that you can't access `$authordata` inside a single post page.
You may try to get author data via `$wp_query`:
```
add_action('wp_head', function()
{
global $wp_query;
$userdata = get_userdata($wp_query->post->post_author);
$avatar_url = get_avatar_ur($userdata->user_email);
...
}, 10, 0);
```
|
231,898 |
<p>I'm using a WP plugin Called <a href="https://wordpress.org/plugins/search-filter/" rel="nofollow">Search and Filter</a> to filter a custom post type — a user directory.</p>
<p>The plugin lets a user filter the directory by specifying terms.</p>
<p>It will also let a user filter the directoy by MULTIPLE terms.</p>
<p>When it does so, I get a slug constructed like this:</p>
<p><a href="http://www.consular-corps-college.org/dir-type/chiefs-of-protocol/?country=united-states-of-america" rel="nofollow">http://www.consular-corps-college.org/dir-type/chiefs-of-protocol/?country=united-states-of-america</a></p>
<p>Posts are returned via the <code>taxonomy.php</code> page.</p>
<p>First, I didn't even know you could do this, so that's cool.</p>
<p>But my question is, how do I display the second term in the slug query?</p>
<p>In other words, I can get the taxonomy.php page to display the term "Chiefs of Protocol" with <code>single_term_title()</code>.</p>
<p>But how can I get WordPress to display the second term which is queried in the slug — in this case "United States of America"?</p>
|
[
{
"answer_id": 231876,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p>The global <code>$authordata</code> variable is only available by default when <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583\" rel=\"nofollow\"><code>$wp_query->is_author() && isset($wp_query->post)</code> condition</a> is satisfied.</p>\n\n<p>It means that you can't access <code>$authordata</code> inside a single post page.</p>\n\n<p>You may try to get author data via <code>$wp_query</code>:</p>\n\n<pre><code>add_action('wp_head', function()\n{\n global $wp_query;\n\n $userdata = get_userdata($wp_query->post->post_author);\n $avatar_url = get_avatar_ur($userdata->user_email);\n ...\n}, 10, 0);\n</code></pre>\n"
},
{
"answer_id": 231894,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>Since the paste has worked perfect for you, let me turn it into an answer.</p>\n\n<p>You can always get the author of a given post with certain methods, let's use <code>get_post_field( 'post_author', $post_id )</code> for this.</p>\n\n<p>To get the data of a given user, there's <a href=\"https://developer.wordpress.org/reference/functions/get_userdata/\" rel=\"nofollow\"><code>get_userdata()</code></a> function to use. We'll pass the author ID as first param to this function to get the author data outside the loop and where the post data are set:</p>\n\n<pre><code>add_action('wp_head', 'mine');\nfunction mine() {\n if ( !is_single() )\n return; // this is not a single post\n\n if ( empty( ( $author = (int) get_post_field( 'post_author', get_the_ID() ) ) ) )\n return; // no author was caught\n\n $authordata = get_userdata( $author );\n\n $avatar_url = get_avatar_url($authordata->user_email);\n // ....\n}\n</code></pre>\n\n<p>This will always work as long as the single post' type is <code>post</code>. To expand to pages, call <code>is_page()</code>, or to custom post types <code>is_singular()</code></p>\n"
}
] |
2016/07/10
|
[
"https://wordpress.stackexchange.com/questions/231898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98107/"
] |
I'm using a WP plugin Called [Search and Filter](https://wordpress.org/plugins/search-filter/) to filter a custom post type — a user directory.
The plugin lets a user filter the directory by specifying terms.
It will also let a user filter the directoy by MULTIPLE terms.
When it does so, I get a slug constructed like this:
<http://www.consular-corps-college.org/dir-type/chiefs-of-protocol/?country=united-states-of-america>
Posts are returned via the `taxonomy.php` page.
First, I didn't even know you could do this, so that's cool.
But my question is, how do I display the second term in the slug query?
In other words, I can get the taxonomy.php page to display the term "Chiefs of Protocol" with `single_term_title()`.
But how can I get WordPress to display the second term which is queried in the slug — in this case "United States of America"?
|
The global `$authordata` variable is only available by default when [`$wp_query->is_author() && isset($wp_query->post)` condition](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583) is satisfied.
It means that you can't access `$authordata` inside a single post page.
You may try to get author data via `$wp_query`:
```
add_action('wp_head', function()
{
global $wp_query;
$userdata = get_userdata($wp_query->post->post_author);
$avatar_url = get_avatar_ur($userdata->user_email);
...
}, 10, 0);
```
|
231,901 |
<p>I've tagged some products with 'tag1', 'tag2' or sometimes both.</p>
<p>I want to list the categories that contain products with a specific tag, so 'Cat1' will only be listed if it has a product that is tagged 'tag1'.</p>
|
[
{
"answer_id": 231876,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p>The global <code>$authordata</code> variable is only available by default when <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583\" rel=\"nofollow\"><code>$wp_query->is_author() && isset($wp_query->post)</code> condition</a> is satisfied.</p>\n\n<p>It means that you can't access <code>$authordata</code> inside a single post page.</p>\n\n<p>You may try to get author data via <code>$wp_query</code>:</p>\n\n<pre><code>add_action('wp_head', function()\n{\n global $wp_query;\n\n $userdata = get_userdata($wp_query->post->post_author);\n $avatar_url = get_avatar_ur($userdata->user_email);\n ...\n}, 10, 0);\n</code></pre>\n"
},
{
"answer_id": 231894,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>Since the paste has worked perfect for you, let me turn it into an answer.</p>\n\n<p>You can always get the author of a given post with certain methods, let's use <code>get_post_field( 'post_author', $post_id )</code> for this.</p>\n\n<p>To get the data of a given user, there's <a href=\"https://developer.wordpress.org/reference/functions/get_userdata/\" rel=\"nofollow\"><code>get_userdata()</code></a> function to use. We'll pass the author ID as first param to this function to get the author data outside the loop and where the post data are set:</p>\n\n<pre><code>add_action('wp_head', 'mine');\nfunction mine() {\n if ( !is_single() )\n return; // this is not a single post\n\n if ( empty( ( $author = (int) get_post_field( 'post_author', get_the_ID() ) ) ) )\n return; // no author was caught\n\n $authordata = get_userdata( $author );\n\n $avatar_url = get_avatar_url($authordata->user_email);\n // ....\n}\n</code></pre>\n\n<p>This will always work as long as the single post' type is <code>post</code>. To expand to pages, call <code>is_page()</code>, or to custom post types <code>is_singular()</code></p>\n"
}
] |
2016/07/10
|
[
"https://wordpress.stackexchange.com/questions/231901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98112/"
] |
I've tagged some products with 'tag1', 'tag2' or sometimes both.
I want to list the categories that contain products with a specific tag, so 'Cat1' will only be listed if it has a product that is tagged 'tag1'.
|
The global `$authordata` variable is only available by default when [`$wp_query->is_author() && isset($wp_query->post)` condition](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583) is satisfied.
It means that you can't access `$authordata` inside a single post page.
You may try to get author data via `$wp_query`:
```
add_action('wp_head', function()
{
global $wp_query;
$userdata = get_userdata($wp_query->post->post_author);
$avatar_url = get_avatar_ur($userdata->user_email);
...
}, 10, 0);
```
|
231,926 |
<p>I'm dynamically generating my category post by getting the Page title and match it with the category name. The category I'm posting sometimes has a subcategory now I need to separate this subcategory by groups. I'm using this code. </p>
<pre><code><ul>
<?php
global $post;
$post_slug = get_the_title();
$args = array ( 'category_name' => $post_slug, 'posts_per_page' => -1, 'orderby' => title, 'order' => ASC);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<strong><?php the_title(); ?></strong>
<?php the_content(); ?>
</li>
<?php endforeach; ?>
</ul>
</code></pre>
<p>I need to call my category only by using the page title. since I'm using a template that post different category and controlling it by name title of the page. Not quite sure if I can convert that to <code>category => ID</code></p>
<p>Please see link <a href="http://prntscr.com/by26xn" rel="nofollow">here</a> for the explanation and mock</p>
<p>Found this <a href="http://www.wpbeginner.com/wp-tutorials/display-subcategories-on-category-pages-in-wordpress/" rel="nofollow">thread</a> not sure if its going to fit on what I did? also this <a href="https://yoast.com/showing-subcategories-on-wordpress-category-pages/" rel="nofollow">one</a> </p>
|
[
{
"answer_id": 231928,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_term_by\" rel=\"nofollow\"><code>get_term_by</code></a> to get a category by <code>name</code>-</p>\n\n<pre><code>$category = get_term_by( 'name', $post_slug, 'category' );\necho $category->term_id;\n</code></pre>\n"
},
{
"answer_id": 232550,
"author": "dg4220",
"author_id": 91201,
"author_profile": "https://wordpress.stackexchange.com/users/91201",
"pm_score": 0,
"selected": false,
"text": "<p>Inside your parent post/category loop use this to generate a list of post titles/category names of the child posts/categories:</p>\n\n<pre><code>$taxonomy_name = 'category';\n$this_term = get_term_by( 'name', get_the_title(), $taxonomy_name );\n\n$term_id = $this_term->term_id;\n$termchildren = get_term_children( $term_id, $taxonomy_name );\n\necho '<ul>';\nforeach ( $termchildren as $child ) {//get the children and search the posts by title\n\n $term = get_term_by( 'id', $child, $taxonomy_name );\n $args = array ( 'post_title' => $term->name, 'orderby' => title, 'order' => ASC);\n $myposts = get_posts( $args );\n foreach( $myposts as $post ) : setup_postdata($post); ?>\n <li>\n <strong><?php the_title(); ?></strong>\n <?php the_content(); ?>\n </li>\n<?php endforeach; ?>\n\n}\necho '</ul>';\n</code></pre>\n\n<p>UPDATE:\nLet's try that again. Inside your parent post/category loop use this . . .</p>\n\n<pre><code>$taxonomy_name = 'category';\n$this_term = get_term_by( 'name', get_the_title( get_the_ID() ), $taxonomy_name );\n\n$categories = get_categories( array(\n 'orderby' => 'name',\n 'child_of' => $this_term->term_ID,\n ) );\n\nif ( ! empty( $categories ) ) {\n\n foreach ( $categories as $category ) {\n $this_post = get_page_by_title( $category->name, OBJECT, 'post');\n echo '<h3>' . $this_post ->post_title . '</h3>';\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 232605,
"author": "yomisimie",
"author_id": 66259,
"author_profile": "https://wordpress.stackexchange.com/users/66259",
"pm_score": 0,
"selected": false,
"text": "<p>Did this before for a website. Here's what i did:<br>\nChecked if there is a category with the same name as the title: </p>\n\n<pre><code>if( term_exists(get_the_title(), 'category' ))\n</code></pre>\n\n<p>If there was one then I got the category by slug: </p>\n\n<pre><code>$cat = get_term_by(\"slug\", $post->post_name, \"category\"); \n</code></pre>\n\n<p>Checked if category had parent or was a parent: </p>\n\n<pre><code>if($cat->parent !== 0) {\n $catID = $cat->parent;\n} else {\n $catID = $cat->term_id;\n} \n</code></pre>\n\n<p>Then retrieved categories by said parent: </p>\n\n<pre><code>$args = array(\n 'type' => 'post',\n 'child_of' => $catID,\n 'hide_empty' => false,\n 'hierarchical' => true,\n 'exclude' => '1'\n );\n$categories = get_categories($args);\n</code></pre>\n\n<p>Then a simple loop with links:</p>\n\n<pre><code>foreach($categories as $categorie) {\n if($categorie->slug == $post->post_name) {\n $clasa = \"class='current'\";\n } else {\n $clasa = \"\";\n }\n echo \"<a \".$clasa.\" href='\".home_url(\"/\").$slug.\"/\".$categorie->slug.\"'>\".$categorie->name.\"</a>\";\n}\n</code></pre>\n\n<p>Hope this is what you are looking for.</p>\n"
}
] |
2016/07/11
|
[
"https://wordpress.stackexchange.com/questions/231926",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62183/"
] |
I'm dynamically generating my category post by getting the Page title and match it with the category name. The category I'm posting sometimes has a subcategory now I need to separate this subcategory by groups. I'm using this code.
```
<ul>
<?php
global $post;
$post_slug = get_the_title();
$args = array ( 'category_name' => $post_slug, 'posts_per_page' => -1, 'orderby' => title, 'order' => ASC);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<strong><?php the_title(); ?></strong>
<?php the_content(); ?>
</li>
<?php endforeach; ?>
</ul>
```
I need to call my category only by using the page title. since I'm using a template that post different category and controlling it by name title of the page. Not quite sure if I can convert that to `category => ID`
Please see link [here](http://prntscr.com/by26xn) for the explanation and mock
Found this [thread](http://www.wpbeginner.com/wp-tutorials/display-subcategories-on-category-pages-in-wordpress/) not sure if its going to fit on what I did? also this [one](https://yoast.com/showing-subcategories-on-wordpress-category-pages/)
|
You can use [`get_term_by`](https://codex.wordpress.org/Function_Reference/get_term_by) to get a category by `name`-
```
$category = get_term_by( 'name', $post_slug, 'category' );
echo $category->term_id;
```
|
231,942 |
<p>I am trying to access a single value from my database through my <code>functions.php</code>. I have tried three different ways to get a result using a dynamic ID and none have worked. I always get NULL as the response. Using a WP_query is not possibility here, so I need to solve this using SQL.</p>
<p><strong>Attempt #1:</strong> </p>
<pre><code>global $post;
global $wpdb;
$post_ID = $post->ID;
$result = $wpdb->get_var($wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_id = %d
AND meta_key = 'wpcf-release-date'
",
$post_ID
) );
</code></pre>
<p><strong>Attempt #2:</strong></p>
<pre><code>$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = $post_ID");
</code></pre>
<p><strong>Attempt #3:</strong> </p>
<pre><code>$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = " . $post_ID);
</code></pre>
<p>I know my query works, I tested the SQL query in Phpmyadmin with a static ID. I can also set the ID manually in my function which will yield a result, but does not help me if it is not dynamic.</p>
<p><strong>SQL Query</strong> </p>
<pre><code>SELECT `meta_value`
FROM `wp_postmeta`
WHERE post_id = 249
AND meta_key = 'wpcf-release-date'
</code></pre>
<p>I assume I am overlooking something simple. </p>
|
[
{
"answer_id": 231947,
"author": "Ehsaan",
"author_id": 54782,
"author_profile": "https://wordpress.stackexchange.com/users/54782",
"pm_score": 2,
"selected": false,
"text": "<p>I tested your all attempts in a shortcode:</p>\n\n<pre><code>function add_test_shortcode() {\n global $wpdb;\n global $post;\n $post_ID = $post->ID;\n $wpdb->show_errors = true;\n $result = $wpdb->get_var('SELECT meta_value FROM '.$wpdb->postmeta.' WHERE meta_key=\"my_test\" AND post_id=' . $post_ID);\n\n return $result;\n}\nadd_shortcode( 'test', 'add_test_shortcode' );\n</code></pre>\n\n<p>It worked perfectly for me, so there might something from your own code:</p>\n\n<h3>1. Check for $post_ID</h3>\n\n<p>Make sure your <code>$post_ID</code> is valid, <code>get_the_ID()</code> might be a better replacement in so many cases than <code>global $post;</code>.</p>\n\n<h3>2. Test your generated query</h3>\n\n<p>You can get your last executed query using <code>$wpdb->last_query</code>, execute it in phpMyAdmin or any other software and check that there is really a result.</p>\n\n<h3>3. Look if there's any error</h3>\n\n<p>You can get the latest error statement using <code>$wpdb->last_error</code>.</p>\n\n<p>My advice to you during WordPress development is that always keep <code>WP_DEBUG</code> on.</p>\n"
},
{
"answer_id": 232009,
"author": "Phawkes",
"author_id": 25506,
"author_profile": "https://wordpress.stackexchange.com/users/25506",
"pm_score": 1,
"selected": true,
"text": "<p>Turns out all of my attempts were viable (Thanks ehsaan for also confirming). The issue was that I was trying to get data from a field that was empty at the time of the function. (I was creating a new/updated post that hadn't updated the field yet).</p>\n\n<p><strong>Solution (delay the hook):</strong></p>\n\n<pre><code>// Time out the custom field to update AFTER the post has been created/updated\nfunction save_custom() {\n global $post;\n $post_ID = $post->ID;\n $result = get_post_meta( $post_ID, 'wpcf-release-date', 1 );\n\n // Add a new key \"era\"\n add_post_meta($post_ID, \"era\", $result, true);\n // If there is already a key \"era\", then update it\n if ( ! add_post_meta($post_ID, \"era\", $result, true) ) { \n update_post_meta( $post_ID, \"era\", $result );\n }\n}\nadd_action('save_post', 'save_custom', 0);\nadd_action('save_post', 'save_custom', 10);\nadd_action('save_post', 'save_custom', 999);\n</code></pre>\n"
}
] |
2016/07/11
|
[
"https://wordpress.stackexchange.com/questions/231942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25506/"
] |
I am trying to access a single value from my database through my `functions.php`. I have tried three different ways to get a result using a dynamic ID and none have worked. I always get NULL as the response. Using a WP\_query is not possibility here, so I need to solve this using SQL.
**Attempt #1:**
```
global $post;
global $wpdb;
$post_ID = $post->ID;
$result = $wpdb->get_var($wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_id = %d
AND meta_key = 'wpcf-release-date'
",
$post_ID
) );
```
**Attempt #2:**
```
$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = $post_ID");
```
**Attempt #3:**
```
$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = " . $post_ID);
```
I know my query works, I tested the SQL query in Phpmyadmin with a static ID. I can also set the ID manually in my function which will yield a result, but does not help me if it is not dynamic.
**SQL Query**
```
SELECT `meta_value`
FROM `wp_postmeta`
WHERE post_id = 249
AND meta_key = 'wpcf-release-date'
```
I assume I am overlooking something simple.
|
Turns out all of my attempts were viable (Thanks ehsaan for also confirming). The issue was that I was trying to get data from a field that was empty at the time of the function. (I was creating a new/updated post that hadn't updated the field yet).
**Solution (delay the hook):**
```
// Time out the custom field to update AFTER the post has been created/updated
function save_custom() {
global $post;
$post_ID = $post->ID;
$result = get_post_meta( $post_ID, 'wpcf-release-date', 1 );
// Add a new key "era"
add_post_meta($post_ID, "era", $result, true);
// If there is already a key "era", then update it
if ( ! add_post_meta($post_ID, "era", $result, true) ) {
update_post_meta( $post_ID, "era", $result );
}
}
add_action('save_post', 'save_custom', 0);
add_action('save_post', 'save_custom', 10);
add_action('save_post', 'save_custom', 999);
```
|
231,976 |
<p>I want to add a new menu point to post that shows posts of a certain category. Adding a new page is easy if it is just a new post type. But I want to only show posts with a specific category and when updating posts make sure the category is checked.</p>
<p>IS there no way of doing this? I was hoping for some simple functon, like the way register_post_type() does it. As there doesn't seem to be, does anyone give me any tips about how to do this? Is it even possible? Or should I just use a custom post type?</p>
|
[
{
"answer_id": 231987,
"author": "Ivijan Stefan Stipić",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 0,
"selected": false,
"text": "<p>You can loop posts by category name or ID:</p>\n\n<pre><code>$query = new WP_Query( array( 'category_name' => 'staff' ) );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$query = new WP_Query( array( 'cat' => 4 ) );\n</code></pre>\n\n<p>and just use good old fashion way to loop:</p>\n\n<pre><code>if ( $query->have_posts() ) :\n while ( $query->have_posts() ) : $query->the_post();\n get_title();\n endwhile;\nelse :\n echo 'No posts';\nendif;\n</code></pre>\n\n<p>You need to create new custom template, get category ID, setup ID in new WP_Query and loop that.</p>\n\n<p>Here is one documentation of how to use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_Query()</a></p>\n"
},
{
"answer_id": 231989,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>You can filter the posts list by appending <code>?category_name=xx</code> to the admin posts list URL, and you can add a submenu page with that URL as the target via <code>add_submenu_page</code>:</p>\n\n<pre><code>add_action( 'admin_menu', 'wpd_admin_menu_item' );\nfunction wpd_admin_menu_item(){\n add_submenu_page(\n 'edit.php',\n 'Page title',\n 'Menu item title',\n 'edit_posts', \n 'edit.php?category_name=somecat'\n );\n}\n</code></pre>\n"
},
{
"answer_id": 256589,
"author": "nu everest",
"author_id": 106850,
"author_profile": "https://wordpress.stackexchange.com/users/106850",
"pm_score": 0,
"selected": false,
"text": "<p>The Category Posts Widget plugin will do this. <a href=\"https://wordpress.org/plugins/category-posts/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/category-posts/</a></p>\n\n<blockquote>\n <p>Category Posts Widget is a light widget designed to do one thing and do it well: display the most recent posts from a certain category.</p>\n</blockquote>\n\n<p><a href=\"http://tiptoppress.com/category-posts-widget/documentation-4-7/?utm_source=wordpress_org&utm_campaign=documentation_4_7_cpw&utm_medium=web\" rel=\"nofollow noreferrer\">Documentation</a> for how to use it.</p>\n\n<p>and</p>\n\n<p>If you want to see how they did it, then this is their <a href=\"https://github.com/tiptoppress/category-posts-widget\" rel=\"nofollow noreferrer\">github repo</a> .</p>\n"
}
] |
2016/07/11
|
[
"https://wordpress.stackexchange.com/questions/231976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98158/"
] |
I want to add a new menu point to post that shows posts of a certain category. Adding a new page is easy if it is just a new post type. But I want to only show posts with a specific category and when updating posts make sure the category is checked.
IS there no way of doing this? I was hoping for some simple functon, like the way register\_post\_type() does it. As there doesn't seem to be, does anyone give me any tips about how to do this? Is it even possible? Or should I just use a custom post type?
|
You can filter the posts list by appending `?category_name=xx` to the admin posts list URL, and you can add a submenu page with that URL as the target via `add_submenu_page`:
```
add_action( 'admin_menu', 'wpd_admin_menu_item' );
function wpd_admin_menu_item(){
add_submenu_page(
'edit.php',
'Page title',
'Menu item title',
'edit_posts',
'edit.php?category_name=somecat'
);
}
```
|
231,995 |
<p>I have a website that displays a slideshow using custom fields and the <a href="http://kenwheeler.github.io/slick/" rel="nofollow">Slick</a> carousel, using the code below. </p>
<pre><code> <?php $entries = get_post_meta( get_the_ID(), '_mysite_homepage_slider_group', true );
foreach ( (array) $entries as $key => $entry ) {
$img = $title = $url = $desc = '';
if ( isset( $entry['_mysite_homepage_slider_title'] ) )
$title = esc_html( $entry['_mysite_homepage_slider_title'] );
if ( isset( $entry['_mysite_homepage_slider_caption'] ) )
$desc = wpautop( $entry['_mysite_homepage_slider_caption'] );
if ( isset( $entry['_mysite_homepage_slider_url'] ) )
$url = esc_html( $entry['_mysite_homepage_slider_url'] );
if ( isset( $entry['_mysite_homepage_slider_image_id'] ) ) {
$img = wp_get_attachment_image_url( $entry['_mysite_homepage_slider_image_id'], 'full');
}
} ?>
</code></pre>
<p>I'd like the user to be able to disable individual slides by clicking a checkbox in the back-end. </p>
<p>Simple enough, right?</p>
<p>So, I added a checkbox and came up with this code to drop in to my snippet. It checks to see if the checkbox is clicked. I tried placing it immediately after the <code>foreach</code> line, like this:</p>
<pre><code> foreach ( (array) $entries as $key => $entry ) {
// Display slides if checkbox is NOT clicked (e.g., is empty)
if ( empty( $entry['_mysite_homepage_slider_checkbox'] ) ) {
$img = $title = $url = $desc = '';
(...)
}
</code></pre>
<p>It kind of works — the slide doesn't show up on the page — but something's still getting through. A duplicate slide is being created.</p>
<p>For example, There are 4 slides in the back end. The 4th has a checkbox that is checked. On the front end, Slide #3 is displayed twice. It appears the code is outputting this:</p>
<ul>
<li>Slide 1 </li>
<li>Slide 2</li>
<li>Slide 3 </li>
<li>Slide 3 (again!)</li>
</ul>
<p>Where have I gone wrong? </p>
<p><strong>EDIT: <a href="https://gist.github.com/madebyelmcity/bc7061b4795c4769d4a1b9cbb3eae970" rel="nofollow">Final code snippet with answer</a></strong>, for anyone who may find this useful in the future. </p>
|
[
{
"answer_id": 232002,
"author": "slashbob",
"author_id": 54908,
"author_profile": "https://wordpress.stackexchange.com/users/54908",
"pm_score": -1,
"selected": false,
"text": "<p>Are all the if-statements that output html actually <em>inside</em> the checkbox if-statement? Can't really tell from the way you've posted the code. It looks like maybe on the last trip through the foreach loop, the values of the variables are being remembered from the previous trip and outputting them again??</p>\n"
},
{
"answer_id": 232018,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": true,
"text": "<p>There's some code missing from your question - the code where your slides are actually output.</p>\n\n<p>The <code>foreach</code> loop you've posted only sets the variables, and the actual output happens below the loop.</p>\n\n<p>So, all you're doing on the fourth slide is avoiding setting the variables... hence the slide is still output, but using the third slide's variables.</p>\n\n<p>Your <code>if</code> checkbox logic looks ok; you just need to include the logic on the actual code that outputs the slides too.</p>\n"
}
] |
2016/07/11
|
[
"https://wordpress.stackexchange.com/questions/231995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52548/"
] |
I have a website that displays a slideshow using custom fields and the [Slick](http://kenwheeler.github.io/slick/) carousel, using the code below.
```
<?php $entries = get_post_meta( get_the_ID(), '_mysite_homepage_slider_group', true );
foreach ( (array) $entries as $key => $entry ) {
$img = $title = $url = $desc = '';
if ( isset( $entry['_mysite_homepage_slider_title'] ) )
$title = esc_html( $entry['_mysite_homepage_slider_title'] );
if ( isset( $entry['_mysite_homepage_slider_caption'] ) )
$desc = wpautop( $entry['_mysite_homepage_slider_caption'] );
if ( isset( $entry['_mysite_homepage_slider_url'] ) )
$url = esc_html( $entry['_mysite_homepage_slider_url'] );
if ( isset( $entry['_mysite_homepage_slider_image_id'] ) ) {
$img = wp_get_attachment_image_url( $entry['_mysite_homepage_slider_image_id'], 'full');
}
} ?>
```
I'd like the user to be able to disable individual slides by clicking a checkbox in the back-end.
Simple enough, right?
So, I added a checkbox and came up with this code to drop in to my snippet. It checks to see if the checkbox is clicked. I tried placing it immediately after the `foreach` line, like this:
```
foreach ( (array) $entries as $key => $entry ) {
// Display slides if checkbox is NOT clicked (e.g., is empty)
if ( empty( $entry['_mysite_homepage_slider_checkbox'] ) ) {
$img = $title = $url = $desc = '';
(...)
}
```
It kind of works — the slide doesn't show up on the page — but something's still getting through. A duplicate slide is being created.
For example, There are 4 slides in the back end. The 4th has a checkbox that is checked. On the front end, Slide #3 is displayed twice. It appears the code is outputting this:
* Slide 1
* Slide 2
* Slide 3
* Slide 3 (again!)
Where have I gone wrong?
**EDIT: [Final code snippet with answer](https://gist.github.com/madebyelmcity/bc7061b4795c4769d4a1b9cbb3eae970)**, for anyone who may find this useful in the future.
|
There's some code missing from your question - the code where your slides are actually output.
The `foreach` loop you've posted only sets the variables, and the actual output happens below the loop.
So, all you're doing on the fourth slide is avoiding setting the variables... hence the slide is still output, but using the third slide's variables.
Your `if` checkbox logic looks ok; you just need to include the logic on the actual code that outputs the slides too.
|
232,029 |
<p>I need help with my <code>query</code> that uses <code>rewind_posts</code> so that if a post is in a particular category, it moves to the top. What I would like to do is have a query that splits posts into a two-column page (left and right divs) and if a post is in a category called <code>First</code>, it's at the top of the list in the left column.</p>
<p>I was able to do this task doing two different <code>queries</code> but I'm having problems merging into one <code>query</code>. I tired to do it myself but the <code>$i++</code> confused me so I'm asking for help on how to merge two separate queries into one.</p>
<p>This is the first <code>query</code> where if any post belongs in a first or second category, they are brought to the top:</p>
<pre><code><?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
)
)
); $query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'First' ) ) : ?>
<?php the_title();?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'Second' ) ) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title(); ?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title();?><br>
<?php endwhile; wp_reset_postdata(); endif; ?>
</code></pre>
<p>This is the <code>query</code> that splits posts into two columns:</p>
<pre><code><?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
))); $wp_query = new WP_Query( $args ); ?>
<div class="left">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
<div id="right">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
</code></pre>
<p>An example of what I'm trying to accomplish:</p>
<pre><code>Title - First | Title
Title - Second | Title
Title | Title
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 232057,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<h2>REWORKED APPROACH</h2>\n\n<p>Due to this becoming a bit of tameletjie due to styling issues, lets rework everything and look at a different approach</p>\n\n<p>I think what we should do here is to rather shuffle the <code>$posts</code> array through <code>usort()</code> to get the posts sorted in the order we want, and then there after we can run the loop normally</p>\n\n<p>Create our query:</p>\n\n<pre><code><?php \n$args = array(\n 'tax_query' => array(\n array(\n 'taxonomy' => 'post-status',\n 'field' => 'slug',\n 'terms' => array ('post-status-published')\n )\n )\n); \n$query = new WP_Query( $args ); \n</code></pre>\n\n<p>Now that we have ran our query, we need to get the <code>$posts</code> property from <code>$query</code> and sort it. So this part will go below our query: (<strong><em>NOTE:</strong> This is completely untested</em>)</p>\n\n<pre><code>if ( $query->have_posts() ) :\n // Now we will use usort to sort the posts array\n @usort( $query->posts, function ( $a, $b ) // @ hides the bug before PHP 7\n {\n // Assign sortable values for categories to sort posts by\n $array = ['a' => $a, 'b' => $b];\n $sort_order_a = '';\n $sort_order_b = '';\n foreach ( $array as $key=>$p ) {\n if ( in_category( 'First', $p ) ) {\n ${'sort_order_' . $key} = 1;\n } elseif ( in_category( 'Second', $p ) ) { \n ${'sort_order_' . $key} = 2;\n } else {\n ${'sort_order_' . $key} = 3;\n }\n }\n\n // Now that we have a custom sorting order, lets sort the posts\n if ( $sort_order_a !== $sort_order_b ) {\n // Make sure about <, change to > to change sort order\n return $sort_order_a < $sort_order_b; \n } else { \n /** \n * Sort by date if sorting order is the same, \n * again, to change sort order, change > to <\n */\n return $a->post_date > $b->post_date;\n }\n });\n\n // Our posts is now sorted, run the loop normally\n // Define our counter to set our columns\n $counter = 0;\n $midpoint = ceil( $query->post_count / 2 );\n\n while ( $query->have_posts() ) :\n $query->the_post();\n // set our left div on first post\n if ( 0 == $counter ) : \n ?>\n <div id=\"left\">\n <?php\n endif;\n\n // Close our left div and open the right one on midpoint\n if ( ( $counter + 1 ) == $midpoint ) :\n <?php\n </div>\n <div id=\"right\">\n <?php\n endif;\n\n // Lets output the posts with different styling\n if ( in_category( 'First', get_the_ID() ) {\n // Apply styling for category First and display title\n the_title();\n } elseif ( in_category( 'First', get_the_ID() ) {\n // Apply styling for category Second and display title\n the_title();\n } else {\n // Apply styling for other posts and display title\n the_title();\n }\n\n /**\n * Lets close the div and bail if we have only one post, \n * or if we are on the last post\n */\n if ( 1 == $post_count \n || ( $counter + 1 ) == $post_count\n ) :\n ?> \n </div>\n <?php\n endif;\n\n // Update our counter\n $counter++;\n\n endwhile;\n wp_reset_postdata();\nendif;\n</code></pre>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>Your second block of code won't work and beats the whole reason for your previous question. Just a note on that code, you should not be using <code>$wp_query</code> as a local variable, it is is a reserved global variable which is intenally used in WordPress to hold the main query object. Breaking this global will break a lot of other stuff. What you are doing is what <code>query_posts()</code> does, that is also why you should never use query posts.</p>\n\n<p>Your issue is that your counter is wrongly updated, thus it wrongly adds your divs. What we need to do is to only update our counder in our conditional statements to prevent posts being double counted and therefor stuufing out layout.</p>\n\n<p>We will only use the first loop and modify that accordingly. The only tricky part will be when to open and close divs</p>\n\n<h1>EDIT</h1>\n\n<p>Due to the code getting a bit techincal, I scrapped my original idea. We will still use the code in block one, except, it would be much easier to loop through the posts as before and create a new array and finally loop through that array and display the posts. </p>\n\n<pre><code><?php \n$args = array(\n 'tax_query' => array(\n array(\n 'taxonomy' => 'post-status',\n 'field' => 'slug',\n 'terms' => array ('post-status-published')\n )\n )\n); \n$query = new WP_Query( $args ); \n\nif ( $query->have_posts() ) :\n\n /**\n * Get the amount of posts in the loop, this will be used\n * to calculate when to open and close our divs\n */\n $post_count = $query->post_count;\n\n /**\n * Get a midpoint to break the div into left and right\n */\n $midpoint = ceil( $post_count / 2 );\n\n $duplicates = []; \n $post_titles = [];\n\n while ( $query->have_posts() ) : \n $query->the_post(); \n\n if ( in_category( 'First' ) ) :\n $post_titles[] = apply_filters( 'the_title', get_the_title() );\n $duplicates[] = get_the_ID(); \n\n endif; \n endwhile; \n\n $query->rewind_posts();\n\n while ( $query->have_posts() ) : \n $query->the_post(); \n\n if ( in_category( 'Second' ) ) : \n if ( in_array( get_the_ID(), $duplicates ) ) \n continue;\n\n $post_titles[] = apply_filters( 'the_title', get_the_title() );\n $duplicates[] = get_the_ID();\n\n endif; \n endwhile;\n\n $query->rewind_posts(); \n\n while ( $query->have_posts() ) : \n $query->the_post();\n\n if ( in_array( get_the_ID(), $duplicates ) ) \n continue; \n\n $post_titles[] = apply_filters( 'the_title', get_the_title() );\n\n endwhile; \n wp_reset_postdata(); \n\n // Now that we have an array of post titles sorted, lets display them\n foreach ( $post_titles as $key=>$post_title ) :\n // Open our left div\n if ( 0 == $key ) : \n ?>\n <div id=\"left\">\n <?php\n endif;\n\n // Close our left div and open the right one on midpoint\n if ( ( $key + 1 ) == $midpoint ) :\n <?php\n </div>\n <div id=\"right\">\n <?php\n endif;\n\n // Display the post title\n echo $post_title . '</br>';\n\n /**\n * Lets close the div and bail if we have only one post, \n * or if we are on the last post\n */\n if ( 1 == $post_count \n || ( $key + 1 ) == $post_count\n ) :\n ?> \n </div>\n <?php\n break;\n endif;\n\n endforeach;\n\nendif; \n?>\n</code></pre>\n\n<h2>IMPORTANT NOTE:</h2>\n\n<p>Al code is untested and can be improved as you see fit. Due to being untested, there might be slight syntax errors or small bugs</p>\n"
},
{
"answer_id": 233419,
"author": "Gregory Schultz",
"author_id": 8049,
"author_profile": "https://wordpress.stackexchange.com/users/8049",
"pm_score": 1,
"selected": true,
"text": "<p>It's complete. This is my final code:</p>\n\n<pre><code>// the query. Only show posts that belong to the taxonomy called \"post-status\" and they have a slug called \"post-status-published\"\n<?php $args = array('tax_query' => array(array('taxonomy' => 'post-status','field' => 'slug','terms' => array ('post-status-published')))); $query = new WP_Query( $args );?>\n\n// the loop. Also gets variables to false and enables the variable \"duplicate\".\n<?php if ( $query->have_posts() ) : $firstonly = false; $major = false; $groupa = false; $groupb = false; $groupc = false; $groupd = false; $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>\n\n\n// checks if any post in the loop belongs to a certain category. If any post with those category is in the loop, the variable is changed to \"true\". Also adds the \"Post ID\" in that category to the \"duplicate\" variable.\n<?php if ( in_category('first') ) : ?>\n <?php $firstonly = true; ?>\n <?php $duplicates[] = get_the_ID(); ?>\n<?php endif; ?>\n<?php if ( in_category(array('major','major-first') ) ) : ?>\n <?php $major = true; ?>\n <?php $duplicates[] = get_the_ID(); ?>\n<?php endif; ?>\n<?php if ( in_category(array('group-a-first','group-a')) ) : ?>\n <?php $groupa = true; ?>\n <?php $duplicates[] = get_the_ID(); ?>\n<?php endif;?>\n<?php if ( in_category(array('group-b-first','group-b')) ) : ?>\n <?php $groupb = true; ?>\n <?php $duplicates[] = get_the_ID(); ?>\n<?php endif;?>\n<?php if ( in_category(array('group-c-first','group-c')) ) : ?>\n <?php $groupc = true; ?>\n <?php $duplicates[] = get_the_ID(); ?>\n<?php endif;?>\n<?php if ( in_category(array('group-d-first','group-d')) ) : ?>\n <?php $groupd = true; ?>\n <?php $duplicates[] = get_the_ID(); ?>\n<?php endif;?>\n\n\n// Close the loop and rewind the query\n<?php endwhile; endif; ?>\n<?php $query->rewind_posts(); ?>\n\n\n// The output of the loop. Only show the output if the above is set to true.\n<?php if ($major == true):?>\n <div class=\"group-major\">\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'major-first'):?>\n <div class=\"major-first\">\n major first - <?php print $postData->post_title;?><br>\n </div>\n <?php endif;?>\n <?php } ?>\n <div class=\"group-sorted\">\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'major'):?>\n <div class=\"post\">\n major - <?php print $postData->post_title;?><br>\n </div>\n <?php endif;?>\n <?php } ?>\n </div></div>\n<?php endif;?>\n<?php if ($firstonly == true):?>\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n first - <?php print $postData->post_title;?><br>\n <?php } ?>\n<?php endif;?>\n<?php if (($groupa == true) or ($groupb == true) or ($groupc == true) or ($groupd == true)):?>\n <?php if (($groupa == true) && ($groupb == false)):?>\n group solo start<br>\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>\n group a first (only) - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n\n <?php else:?>\n group multi start<br>\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>\n group a first (multi) - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n\n <?php endif;?>\n\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a'):?>\n group a - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-b-first'):?>\n group b first - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-b'):?>\n group b - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n\n <?php if (( true == $groupa ) && (false == $groupb) && (false == $groupc) && (false == $groupd)) :?>\n solo end<br>\n <?php endif;?>\n <?php if (( true == $groupa ) && (true == $groupb) && (false == $groupc) && (false == $groupd)) :?>\n group b multi end<br>\n <?php endif;?>\n\n\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-c-first'):?>\n group c first - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-c'):?>\n group c - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n\n <?php if (( true == $groupa ) && (true == $groupb) && (true == $groupc) && ($groupd == false)) :?>\n group c multi end<br>\n <?php endif;?>\n\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-d-first'):?>\n group d first - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n <?php foreach($duplicates as $postID) { ?>\n <?php $postData = get_post( $postID );?>\n <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-d'):?>\n group d - <?php print $postData->post_title;?><br>\n <?php endif;?>\n <?php } ?>\n\n <?php if (( true == $groupa ) && (true == $groupb) && (true == $groupc) && ($groupd == true)) :?>\n group d multi end<br>\n <?php endif;?>\n\n<?php endif;?>\n\n//the second loop. Also sets two columns\n<?php $row_start = 1; while ( $query->have_posts() ) : $query->the_post();?>\n\n // if the category \"first\" is set to true, split posts into columns with most posts favoring the left. I.E. if the loop has ten posts, it is evenly split. If not, the split favors the right side.\n <?php if(true == $firstonly):?>\n <?php if(in_array( get_the_ID(), $duplicates ) ) continue; ?>\n <?php if($row_start % 2 != 0 && $row_start != ($sum_total = $wp_query->found_posts - count($duplicates))):?>\n <?php $left[] = get_the_ID();?>\n <?php else:?>\n <?php $right[] = get_the_ID();?>\n <?php endif;?>\n <?php else:?>\n <?php if(in_array( get_the_ID(), $duplicates ) ) continue; ?>\n <?php if($row_start % 2 != 0):?>\n <?php $left[] = get_the_ID();?>\n <?php else:?>\n <?php $right[] = get_the_ID();?>\n <?php endif;?>\n <?php endif;?>\n\n// end the column, the loop, the query and reset the query. \n<?php ++$row_start; endwhile; wp_reset_postdata();?>\n\n// the output of the second loop. \n<?php foreach($left as $postID) { ;?>\n <?php $postData = get_post( $postID );?>\n left - <?php print $postData->post_title;?><br>\n<?php } ?>\n<?php foreach($right as $postID) { ;?>\n <?php $postData = get_post( $postID );?>\n right - <?php print $postData->post_title;?><br>\n<?php } ?>\n</code></pre>\n\n<p>Thanks everyone for the help! This is probably the most complex problem I've ever encountered. Thank you so much for the help!</p>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232029",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8049/"
] |
I need help with my `query` that uses `rewind_posts` so that if a post is in a particular category, it moves to the top. What I would like to do is have a query that splits posts into a two-column page (left and right divs) and if a post is in a category called `First`, it's at the top of the list in the left column.
I was able to do this task doing two different `queries` but I'm having problems merging into one `query`. I tired to do it myself but the `$i++` confused me so I'm asking for help on how to merge two separate queries into one.
This is the first `query` where if any post belongs in a first or second category, they are brought to the top:
```
<?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
)
)
); $query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'First' ) ) : ?>
<?php the_title();?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'Second' ) ) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title(); ?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title();?><br>
<?php endwhile; wp_reset_postdata(); endif; ?>
```
This is the `query` that splits posts into two columns:
```
<?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
))); $wp_query = new WP_Query( $args ); ?>
<div class="left">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
<div id="right">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
```
An example of what I'm trying to accomplish:
```
Title - First | Title
Title - Second | Title
Title | Title
```
Thanks!
|
It's complete. This is my final code:
```
// the query. Only show posts that belong to the taxonomy called "post-status" and they have a slug called "post-status-published"
<?php $args = array('tax_query' => array(array('taxonomy' => 'post-status','field' => 'slug','terms' => array ('post-status-published')))); $query = new WP_Query( $args );?>
// the loop. Also gets variables to false and enables the variable "duplicate".
<?php if ( $query->have_posts() ) : $firstonly = false; $major = false; $groupa = false; $groupb = false; $groupc = false; $groupd = false; $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>
// checks if any post in the loop belongs to a certain category. If any post with those category is in the loop, the variable is changed to "true". Also adds the "Post ID" in that category to the "duplicate" variable.
<?php if ( in_category('first') ) : ?>
<?php $firstonly = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; ?>
<?php if ( in_category(array('major','major-first') ) ) : ?>
<?php $major = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; ?>
<?php if ( in_category(array('group-a-first','group-a')) ) : ?>
<?php $groupa = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
<?php if ( in_category(array('group-b-first','group-b')) ) : ?>
<?php $groupb = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
<?php if ( in_category(array('group-c-first','group-c')) ) : ?>
<?php $groupc = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
<?php if ( in_category(array('group-d-first','group-d')) ) : ?>
<?php $groupd = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
// Close the loop and rewind the query
<?php endwhile; endif; ?>
<?php $query->rewind_posts(); ?>
// The output of the loop. Only show the output if the above is set to true.
<?php if ($major == true):?>
<div class="group-major">
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'major-first'):?>
<div class="major-first">
major first - <?php print $postData->post_title;?><br>
</div>
<?php endif;?>
<?php } ?>
<div class="group-sorted">
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'major'):?>
<div class="post">
major - <?php print $postData->post_title;?><br>
</div>
<?php endif;?>
<?php } ?>
</div></div>
<?php endif;?>
<?php if ($firstonly == true):?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
first - <?php print $postData->post_title;?><br>
<?php } ?>
<?php endif;?>
<?php if (($groupa == true) or ($groupb == true) or ($groupc == true) or ($groupd == true)):?>
<?php if (($groupa == true) && ($groupb == false)):?>
group solo start<br>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>
group a first (only) - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php else:?>
group multi start<br>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>
group a first (multi) - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php endif;?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a'):?>
group a - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-b-first'):?>
group b first - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-b'):?>
group b - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php if (( true == $groupa ) && (false == $groupb) && (false == $groupc) && (false == $groupd)) :?>
solo end<br>
<?php endif;?>
<?php if (( true == $groupa ) && (true == $groupb) && (false == $groupc) && (false == $groupd)) :?>
group b multi end<br>
<?php endif;?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-c-first'):?>
group c first - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-c'):?>
group c - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php if (( true == $groupa ) && (true == $groupb) && (true == $groupc) && ($groupd == false)) :?>
group c multi end<br>
<?php endif;?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-d-first'):?>
group d first - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-d'):?>
group d - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php if (( true == $groupa ) && (true == $groupb) && (true == $groupc) && ($groupd == true)) :?>
group d multi end<br>
<?php endif;?>
<?php endif;?>
//the second loop. Also sets two columns
<?php $row_start = 1; while ( $query->have_posts() ) : $query->the_post();?>
// if the category "first" is set to true, split posts into columns with most posts favoring the left. I.E. if the loop has ten posts, it is evenly split. If not, the split favors the right side.
<?php if(true == $firstonly):?>
<?php if(in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php if($row_start % 2 != 0 && $row_start != ($sum_total = $wp_query->found_posts - count($duplicates))):?>
<?php $left[] = get_the_ID();?>
<?php else:?>
<?php $right[] = get_the_ID();?>
<?php endif;?>
<?php else:?>
<?php if(in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php if($row_start % 2 != 0):?>
<?php $left[] = get_the_ID();?>
<?php else:?>
<?php $right[] = get_the_ID();?>
<?php endif;?>
<?php endif;?>
// end the column, the loop, the query and reset the query.
<?php ++$row_start; endwhile; wp_reset_postdata();?>
// the output of the second loop.
<?php foreach($left as $postID) { ;?>
<?php $postData = get_post( $postID );?>
left - <?php print $postData->post_title;?><br>
<?php } ?>
<?php foreach($right as $postID) { ;?>
<?php $postData = get_post( $postID );?>
right - <?php print $postData->post_title;?><br>
<?php } ?>
```
Thanks everyone for the help! This is probably the most complex problem I've ever encountered. Thank you so much for the help!
|
232,038 |
<p>We are running several sub-domain sites on a WordPress Multisite environment and want to switch the primary site from the root to a sub-domain like so:</p>
<p>Current site is <code>example.com</code> with <code>ID 1</code> (cannot rename because field is set and uneditable)</p>
<p>New site is <code>new.example.com</code> with <code>ID 15</code> (tried to rename to <code>example.com</code>)</p>
<p>I followed some instructions for switching that involved renaming the sites and updating the <code>wp-config.php</code> file to give the new ID of 15 for the <code>SITE_ID_CURRENT_SITE</code> and <code>Blog_ID_CURRENT_SITE</code>. The result was the main site did not change and the admin got mucked up.</p>
<p>Is there a straight forward way to switch the main site out and replace it with the sub-domain site content without importing posts/pages and plugins?</p>
<hr>
<p>UPDATE:</p>
<p>Thanks for giving these tips. My conclusion with what I've seen in the database, read, and get from you is that the new subdomain site to replace the main site needs to have the base table names and ID of 1, updated paths etc. My only worry is that after switching these the network admin will have a problem -- so I basically need to compare the base tables (wp_options etc) to the equivalent (wp_x_options etc) to see if there is anything unique related to the network admin in those base tables.</p>
|
[
{
"answer_id": 235578,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 4,
"selected": false,
"text": "<p><del>Four years old and no answer? So here we go…-</del></p>\n\n<p>Let's take the following network setup as example (I'm using WP-CLI's <a href=\"http://wp-cli.org/commands/site/list/\" rel=\"noreferrer\">site list command</a>):</p>\n\n<pre><code>$ wp site list\n+---------+--------------------+---------------------+---------------------+\n| blog_id | url | last_updated | registered |\n+---------+--------------------+---------------------+---------------------+\n| 1 | http://wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |\n| 2 | http://foo.wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |\n+---------+--------------------+---------------------+---------------------+\n</code></pre>\n\n<p>The network site list would look like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7JKuQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7JKuQ.png\" alt=\"network site list\"></a></p>\n\n<p>We want to use the site with ID <code>2</code> as the new root site with the URL <code>http://wp.tmp/</code>. This is actually the same problem as described in the question just with some other values for the ID and the URLs.</p>\n\n<p>The multisite relevant part of the <code>wp-config.php</code> looks probably like this:</p>\n\n<pre><code>const MULTISITE = TRUE;\nconst DOMAIN_CURRENT_SITE = 'wp.tmp';\nconst PATH_CURRENT_SITE = '/';\nconst SITE_ID_CURRENT_SITE = 1;\nconst BLOG_ID_CURRENT_SITE = 1;\nconst SUBDOMAIN_INSTALL = TRUE;\n</code></pre>\n\n<h2>Updating database site settings</h2>\n\n<p>WordPress uses the tables <code>wp_*_option</code> and <code>wp_blogs</code> to find the matching blog for a given request URL and to build proper permalinks for this blog. So we have to change the values in the following three tables (for this example):</p>\n\n<ul>\n<li>In <code>wp_options</code> the keys <code>home</code> and <code>siteurl</code></li>\n<li>In <code>wp_2_options</code> the keys <code>home</code> and <code>siteurl</code> (in your case this would be <code>wp_15_options</code>)</li>\n<li>In <code>wp_blogs</code> the column <code>domain</code> for both sites with ID <code>1</code> and <code>2</code> (respectively <code>15</code>)</li>\n</ul>\n\n<p>I'm using Adminer for this, but any other DB management tool (PhpMyAdmin) does the job as well. (The screenshots shows the GUI in German language but I guess the idea is clear.)</p>\n\n<p><a href=\"https://i.stack.imgur.com/169Pa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/169Pa.png\" alt=\"adminer edit wp_options\"></a></p>\n\n<p>In <code>wp_options</code> (the options table for site ID <code>1</code>) I changed the values of both keys <code>home</code> and <code>siteurl</code> from <code>http://wp.tmp</code> to <code>http://foo.wp.tmp</code>. (The screenshot above shows the state before the update.)</p>\n\n<p>I did exactly the same with the table <code>wp_2_options</code> but here I changed the value from <code>http://foo.wp.tmp</code> to <code>http://wp.tmp</code>.</p>\n\n<p>Next step is to update the table <code>wp_blogs</code>: </p>\n\n<p><a href=\"https://i.stack.imgur.com/3I5AJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3I5AJ.png\" alt=\"adminer edit wp_blogs\"></a>\n(Again, the screenshot shows the table before I made any change.) Here you simply switch the values from both sites in the <code>domain</code> column:</p>\n\n<ul>\n<li><code>wp.tmp</code> becomes <code>foo.wp.tmp</code> and</li>\n<li><code>foo.wp.tmp</code> becomes <code>wp.tmp</code></li>\n</ul>\n\n<p>Now you have to update the <code>wp-config.php</code> to deal correctly with the new settings data:</p>\n\n<pre><code>const MULTISITE = TRUE;\nconst DOMAIN_CURRENT_SITE = 'wp.tmp';\nconst PATH_CURRENT_SITE = '/';\nconst SITE_ID_CURRENT_SITE = 1;\nconst BLOG_ID_CURRENT_SITE = 2; // This is the new root site ID\nconst SUBDOMAIN_INSTALL = TRUE;\n</code></pre>\n\n<p>At this point you have again a working WordPress multisite but with a new root site:</p>\n\n<pre><code>$ wp site list\n+---------+--------------------+---------------------+---------------------+\n| blog_id | url | last_updated | registered |\n+---------+--------------------+---------------------+---------------------+\n| 1 | http://foo.wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |\n| 2 | http://wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |\n+---------+--------------------+---------------------+---------------------+\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/f9VwJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/f9VwJ.png\" alt=\"network site list updated\"></a></p>\n\n<p>Remember: during this process, your site will be not available and requests will end up in some nasty errors so you might want to arrange a <code>503 Service Unavailable</code> response in front of your WordPress installation. This could be done <a href=\"http://www.electrictoolbox.com/503-header-apache-htaccess/\" rel=\"noreferrer\">using <code>.htaccess</code></a>.</p>\n\n<h2>Updating database content</h2>\n\n<p>Now comes the tricky part. At the moment, all URLs in the <em>content tables</em> are still pointing to the resources of the old sites. But replacing them is not that easy: Replacing every <code>http://foo.wp.tmp</code> with <code>http://wp.tmp</code> in the first step and every <code>http://wp.tmp</code> with <code>http://foo.wp.tmp</code> in the next step will end up in having all former URLs pointing to site ID 1 (<code>http://foo.wp.tmp</code>).</p>\n\n<p>The best way would be to insert an intermediate step:</p>\n\n<ul>\n<li>Search for <code>http://foo.wp.tmp</code> and replace it with a preferably unique slug: <code>http://3a4b522a.wp.tmp</code></li>\n<li>Search for <code>http://wp.tmp</code> and replace it with <code>http://foo.wp.tmp</code></li>\n<li>Search for <code>http://3a4b522a.wp.tmp</code> and replace it with <code>http://wp.tmp</code></li>\n</ul>\n\n<p>All these search and replace commands should ignore the three tables (<code>*_options</code> <code>*_blogs</code>) we updated before, otherwise they would break the configuration. You might also have a manual look for URLs in <code>wp_*_options</code> table outside of the <code>home</code> and <code>siteurl</code> keys.</p>\n\n<p>I would suggest to use WP-CLI's <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">search-replace command</a> for this as it can deal with serialized data and has no limitations that HTTP might have. </p>\n"
},
{
"answer_id": 320178,
"author": "SuperAtic",
"author_id": 74492,
"author_profile": "https://wordpress.stackexchange.com/users/74492",
"pm_score": 2,
"selected": false,
"text": "<p>An easier alternative (that doesn't involve touching any line of code) is to use the <a href=\"https://wordpress.org/plugins/all-in-one-wp-migration/\" rel=\"nofollow noreferrer\">all-in-one-migration</a> plugin: </p>\n\n<ol>\n<li>export <code>new.example.com</code> with <code>ID 15</code>and </li>\n<li>re-import it into <code>example.com</code> with <code>ID 1</code></li>\n</ol>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98186/"
] |
We are running several sub-domain sites on a WordPress Multisite environment and want to switch the primary site from the root to a sub-domain like so:
Current site is `example.com` with `ID 1` (cannot rename because field is set and uneditable)
New site is `new.example.com` with `ID 15` (tried to rename to `example.com`)
I followed some instructions for switching that involved renaming the sites and updating the `wp-config.php` file to give the new ID of 15 for the `SITE_ID_CURRENT_SITE` and `Blog_ID_CURRENT_SITE`. The result was the main site did not change and the admin got mucked up.
Is there a straight forward way to switch the main site out and replace it with the sub-domain site content without importing posts/pages and plugins?
---
UPDATE:
Thanks for giving these tips. My conclusion with what I've seen in the database, read, and get from you is that the new subdomain site to replace the main site needs to have the base table names and ID of 1, updated paths etc. My only worry is that after switching these the network admin will have a problem -- so I basically need to compare the base tables (wp\_options etc) to the equivalent (wp\_x\_options etc) to see if there is anything unique related to the network admin in those base tables.
|
~~Four years old and no answer? So here we go…-~~
Let's take the following network setup as example (I'm using WP-CLI's [site list command](http://wp-cli.org/commands/site/list/)):
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://foo.wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
The network site list would look like this:
[](https://i.stack.imgur.com/7JKuQ.png)
We want to use the site with ID `2` as the new root site with the URL `http://wp.tmp/`. This is actually the same problem as described in the question just with some other values for the ID and the URLs.
The multisite relevant part of the `wp-config.php` looks probably like this:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 1;
const SUBDOMAIN_INSTALL = TRUE;
```
Updating database site settings
-------------------------------
WordPress uses the tables `wp_*_option` and `wp_blogs` to find the matching blog for a given request URL and to build proper permalinks for this blog. So we have to change the values in the following three tables (for this example):
* In `wp_options` the keys `home` and `siteurl`
* In `wp_2_options` the keys `home` and `siteurl` (in your case this would be `wp_15_options`)
* In `wp_blogs` the column `domain` for both sites with ID `1` and `2` (respectively `15`)
I'm using Adminer for this, but any other DB management tool (PhpMyAdmin) does the job as well. (The screenshots shows the GUI in German language but I guess the idea is clear.)
[](https://i.stack.imgur.com/169Pa.png)
In `wp_options` (the options table for site ID `1`) I changed the values of both keys `home` and `siteurl` from `http://wp.tmp` to `http://foo.wp.tmp`. (The screenshot above shows the state before the update.)
I did exactly the same with the table `wp_2_options` but here I changed the value from `http://foo.wp.tmp` to `http://wp.tmp`.
Next step is to update the table `wp_blogs`:
[](https://i.stack.imgur.com/3I5AJ.png)
(Again, the screenshot shows the table before I made any change.) Here you simply switch the values from both sites in the `domain` column:
* `wp.tmp` becomes `foo.wp.tmp` and
* `foo.wp.tmp` becomes `wp.tmp`
Now you have to update the `wp-config.php` to deal correctly with the new settings data:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 2; // This is the new root site ID
const SUBDOMAIN_INSTALL = TRUE;
```
At this point you have again a working WordPress multisite but with a new root site:
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://foo.wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
[](https://i.stack.imgur.com/f9VwJ.png)
Remember: during this process, your site will be not available and requests will end up in some nasty errors so you might want to arrange a `503 Service Unavailable` response in front of your WordPress installation. This could be done [using `.htaccess`](http://www.electrictoolbox.com/503-header-apache-htaccess/).
Updating database content
-------------------------
Now comes the tricky part. At the moment, all URLs in the *content tables* are still pointing to the resources of the old sites. But replacing them is not that easy: Replacing every `http://foo.wp.tmp` with `http://wp.tmp` in the first step and every `http://wp.tmp` with `http://foo.wp.tmp` in the next step will end up in having all former URLs pointing to site ID 1 (`http://foo.wp.tmp`).
The best way would be to insert an intermediate step:
* Search for `http://foo.wp.tmp` and replace it with a preferably unique slug: `http://3a4b522a.wp.tmp`
* Search for `http://wp.tmp` and replace it with `http://foo.wp.tmp`
* Search for `http://3a4b522a.wp.tmp` and replace it with `http://wp.tmp`
All these search and replace commands should ignore the three tables (`*_options` `*_blogs`) we updated before, otherwise they would break the configuration. You might also have a manual look for URLs in `wp_*_options` table outside of the `home` and `siteurl` keys.
I would suggest to use WP-CLI's [search-replace command](http://wp-cli.org/) for this as it can deal with serialized data and has no limitations that HTTP might have.
|
232,051 |
<p>Many users do not compress or resize their images before uploading them into a post, so source images can often be a lot larger than the settings in /wp-admin/options-media.php.</p>
<p>Many theme and plugin authors do not respect the default settings in /wp-admin/options-media.php and often do not create custom sizes for things like gallery sliders.</p>
<p>The result is huge-ass images on pages and a slower internet.</p>
<p>WordPress provides 3 default image sizes and allows theme authors to create custom sizes as needed. </p>
<p>Does anyone know how to force WordPress, themes and plugins into using defined sizes in /wp-admin/options-media.php and/ or custom sizes created with add_image_size?</p>
<p>I've seen a few posts on here about deleting original source files, but it seems to me that leaving the original images on the server is nice a reference and fallback for re-cutting with <a href="https://wordpress.org/plugins/regenerate-thumbnails/" rel="nofollow">Regenerate Thumbnails</a> later if you need to change themes at a later date.</p>
|
[
{
"answer_id": 235578,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 4,
"selected": false,
"text": "<p><del>Four years old and no answer? So here we go…-</del></p>\n\n<p>Let's take the following network setup as example (I'm using WP-CLI's <a href=\"http://wp-cli.org/commands/site/list/\" rel=\"noreferrer\">site list command</a>):</p>\n\n<pre><code>$ wp site list\n+---------+--------------------+---------------------+---------------------+\n| blog_id | url | last_updated | registered |\n+---------+--------------------+---------------------+---------------------+\n| 1 | http://wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |\n| 2 | http://foo.wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |\n+---------+--------------------+---------------------+---------------------+\n</code></pre>\n\n<p>The network site list would look like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7JKuQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7JKuQ.png\" alt=\"network site list\"></a></p>\n\n<p>We want to use the site with ID <code>2</code> as the new root site with the URL <code>http://wp.tmp/</code>. This is actually the same problem as described in the question just with some other values for the ID and the URLs.</p>\n\n<p>The multisite relevant part of the <code>wp-config.php</code> looks probably like this:</p>\n\n<pre><code>const MULTISITE = TRUE;\nconst DOMAIN_CURRENT_SITE = 'wp.tmp';\nconst PATH_CURRENT_SITE = '/';\nconst SITE_ID_CURRENT_SITE = 1;\nconst BLOG_ID_CURRENT_SITE = 1;\nconst SUBDOMAIN_INSTALL = TRUE;\n</code></pre>\n\n<h2>Updating database site settings</h2>\n\n<p>WordPress uses the tables <code>wp_*_option</code> and <code>wp_blogs</code> to find the matching blog for a given request URL and to build proper permalinks for this blog. So we have to change the values in the following three tables (for this example):</p>\n\n<ul>\n<li>In <code>wp_options</code> the keys <code>home</code> and <code>siteurl</code></li>\n<li>In <code>wp_2_options</code> the keys <code>home</code> and <code>siteurl</code> (in your case this would be <code>wp_15_options</code>)</li>\n<li>In <code>wp_blogs</code> the column <code>domain</code> for both sites with ID <code>1</code> and <code>2</code> (respectively <code>15</code>)</li>\n</ul>\n\n<p>I'm using Adminer for this, but any other DB management tool (PhpMyAdmin) does the job as well. (The screenshots shows the GUI in German language but I guess the idea is clear.)</p>\n\n<p><a href=\"https://i.stack.imgur.com/169Pa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/169Pa.png\" alt=\"adminer edit wp_options\"></a></p>\n\n<p>In <code>wp_options</code> (the options table for site ID <code>1</code>) I changed the values of both keys <code>home</code> and <code>siteurl</code> from <code>http://wp.tmp</code> to <code>http://foo.wp.tmp</code>. (The screenshot above shows the state before the update.)</p>\n\n<p>I did exactly the same with the table <code>wp_2_options</code> but here I changed the value from <code>http://foo.wp.tmp</code> to <code>http://wp.tmp</code>.</p>\n\n<p>Next step is to update the table <code>wp_blogs</code>: </p>\n\n<p><a href=\"https://i.stack.imgur.com/3I5AJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3I5AJ.png\" alt=\"adminer edit wp_blogs\"></a>\n(Again, the screenshot shows the table before I made any change.) Here you simply switch the values from both sites in the <code>domain</code> column:</p>\n\n<ul>\n<li><code>wp.tmp</code> becomes <code>foo.wp.tmp</code> and</li>\n<li><code>foo.wp.tmp</code> becomes <code>wp.tmp</code></li>\n</ul>\n\n<p>Now you have to update the <code>wp-config.php</code> to deal correctly with the new settings data:</p>\n\n<pre><code>const MULTISITE = TRUE;\nconst DOMAIN_CURRENT_SITE = 'wp.tmp';\nconst PATH_CURRENT_SITE = '/';\nconst SITE_ID_CURRENT_SITE = 1;\nconst BLOG_ID_CURRENT_SITE = 2; // This is the new root site ID\nconst SUBDOMAIN_INSTALL = TRUE;\n</code></pre>\n\n<p>At this point you have again a working WordPress multisite but with a new root site:</p>\n\n<pre><code>$ wp site list\n+---------+--------------------+---------------------+---------------------+\n| blog_id | url | last_updated | registered |\n+---------+--------------------+---------------------+---------------------+\n| 1 | http://foo.wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |\n| 2 | http://wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |\n+---------+--------------------+---------------------+---------------------+\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/f9VwJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/f9VwJ.png\" alt=\"network site list updated\"></a></p>\n\n<p>Remember: during this process, your site will be not available and requests will end up in some nasty errors so you might want to arrange a <code>503 Service Unavailable</code> response in front of your WordPress installation. This could be done <a href=\"http://www.electrictoolbox.com/503-header-apache-htaccess/\" rel=\"noreferrer\">using <code>.htaccess</code></a>.</p>\n\n<h2>Updating database content</h2>\n\n<p>Now comes the tricky part. At the moment, all URLs in the <em>content tables</em> are still pointing to the resources of the old sites. But replacing them is not that easy: Replacing every <code>http://foo.wp.tmp</code> with <code>http://wp.tmp</code> in the first step and every <code>http://wp.tmp</code> with <code>http://foo.wp.tmp</code> in the next step will end up in having all former URLs pointing to site ID 1 (<code>http://foo.wp.tmp</code>).</p>\n\n<p>The best way would be to insert an intermediate step:</p>\n\n<ul>\n<li>Search for <code>http://foo.wp.tmp</code> and replace it with a preferably unique slug: <code>http://3a4b522a.wp.tmp</code></li>\n<li>Search for <code>http://wp.tmp</code> and replace it with <code>http://foo.wp.tmp</code></li>\n<li>Search for <code>http://3a4b522a.wp.tmp</code> and replace it with <code>http://wp.tmp</code></li>\n</ul>\n\n<p>All these search and replace commands should ignore the three tables (<code>*_options</code> <code>*_blogs</code>) we updated before, otherwise they would break the configuration. You might also have a manual look for URLs in <code>wp_*_options</code> table outside of the <code>home</code> and <code>siteurl</code> keys.</p>\n\n<p>I would suggest to use WP-CLI's <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">search-replace command</a> for this as it can deal with serialized data and has no limitations that HTTP might have. </p>\n"
},
{
"answer_id": 320178,
"author": "SuperAtic",
"author_id": 74492,
"author_profile": "https://wordpress.stackexchange.com/users/74492",
"pm_score": 2,
"selected": false,
"text": "<p>An easier alternative (that doesn't involve touching any line of code) is to use the <a href=\"https://wordpress.org/plugins/all-in-one-wp-migration/\" rel=\"nofollow noreferrer\">all-in-one-migration</a> plugin: </p>\n\n<ol>\n<li>export <code>new.example.com</code> with <code>ID 15</code>and </li>\n<li>re-import it into <code>example.com</code> with <code>ID 1</code></li>\n</ol>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1341/"
] |
Many users do not compress or resize their images before uploading them into a post, so source images can often be a lot larger than the settings in /wp-admin/options-media.php.
Many theme and plugin authors do not respect the default settings in /wp-admin/options-media.php and often do not create custom sizes for things like gallery sliders.
The result is huge-ass images on pages and a slower internet.
WordPress provides 3 default image sizes and allows theme authors to create custom sizes as needed.
Does anyone know how to force WordPress, themes and plugins into using defined sizes in /wp-admin/options-media.php and/ or custom sizes created with add\_image\_size?
I've seen a few posts on here about deleting original source files, but it seems to me that leaving the original images on the server is nice a reference and fallback for re-cutting with [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) later if you need to change themes at a later date.
|
~~Four years old and no answer? So here we go…-~~
Let's take the following network setup as example (I'm using WP-CLI's [site list command](http://wp-cli.org/commands/site/list/)):
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://foo.wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
The network site list would look like this:
[](https://i.stack.imgur.com/7JKuQ.png)
We want to use the site with ID `2` as the new root site with the URL `http://wp.tmp/`. This is actually the same problem as described in the question just with some other values for the ID and the URLs.
The multisite relevant part of the `wp-config.php` looks probably like this:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 1;
const SUBDOMAIN_INSTALL = TRUE;
```
Updating database site settings
-------------------------------
WordPress uses the tables `wp_*_option` and `wp_blogs` to find the matching blog for a given request URL and to build proper permalinks for this blog. So we have to change the values in the following three tables (for this example):
* In `wp_options` the keys `home` and `siteurl`
* In `wp_2_options` the keys `home` and `siteurl` (in your case this would be `wp_15_options`)
* In `wp_blogs` the column `domain` for both sites with ID `1` and `2` (respectively `15`)
I'm using Adminer for this, but any other DB management tool (PhpMyAdmin) does the job as well. (The screenshots shows the GUI in German language but I guess the idea is clear.)
[](https://i.stack.imgur.com/169Pa.png)
In `wp_options` (the options table for site ID `1`) I changed the values of both keys `home` and `siteurl` from `http://wp.tmp` to `http://foo.wp.tmp`. (The screenshot above shows the state before the update.)
I did exactly the same with the table `wp_2_options` but here I changed the value from `http://foo.wp.tmp` to `http://wp.tmp`.
Next step is to update the table `wp_blogs`:
[](https://i.stack.imgur.com/3I5AJ.png)
(Again, the screenshot shows the table before I made any change.) Here you simply switch the values from both sites in the `domain` column:
* `wp.tmp` becomes `foo.wp.tmp` and
* `foo.wp.tmp` becomes `wp.tmp`
Now you have to update the `wp-config.php` to deal correctly with the new settings data:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 2; // This is the new root site ID
const SUBDOMAIN_INSTALL = TRUE;
```
At this point you have again a working WordPress multisite but with a new root site:
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://foo.wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
[](https://i.stack.imgur.com/f9VwJ.png)
Remember: during this process, your site will be not available and requests will end up in some nasty errors so you might want to arrange a `503 Service Unavailable` response in front of your WordPress installation. This could be done [using `.htaccess`](http://www.electrictoolbox.com/503-header-apache-htaccess/).
Updating database content
-------------------------
Now comes the tricky part. At the moment, all URLs in the *content tables* are still pointing to the resources of the old sites. But replacing them is not that easy: Replacing every `http://foo.wp.tmp` with `http://wp.tmp` in the first step and every `http://wp.tmp` with `http://foo.wp.tmp` in the next step will end up in having all former URLs pointing to site ID 1 (`http://foo.wp.tmp`).
The best way would be to insert an intermediate step:
* Search for `http://foo.wp.tmp` and replace it with a preferably unique slug: `http://3a4b522a.wp.tmp`
* Search for `http://wp.tmp` and replace it with `http://foo.wp.tmp`
* Search for `http://3a4b522a.wp.tmp` and replace it with `http://wp.tmp`
All these search and replace commands should ignore the three tables (`*_options` `*_blogs`) we updated before, otherwise they would break the configuration. You might also have a manual look for URLs in `wp_*_options` table outside of the `home` and `siteurl` keys.
I would suggest to use WP-CLI's [search-replace command](http://wp-cli.org/) for this as it can deal with serialized data and has no limitations that HTTP might have.
|
232,055 |
<p>I want to get the list of all available hooks from active theme / from a specific plugin.</p>
<p>I was tried to get it from global variables <code>$wp_actions & $wp_filter</code> But, They are showing all registered hooks.</p>
<p>E.g.</p>
<pre><code>global $wp_actions, $wp_filter;
echo '<pre>';
print_r($wp_filter);
</code></pre>
<p>E.g. If theme or plugin register the action in <code>after_setup_theme</code> then it'll list in <code>[after_setup_theme]</code> key from <code>global $wp_filter</code>.</p>
<p>I was tried one of the best plugin <code>Simply Show Hooks</code>. But, It'll also, show all the registered hooks.</p>
<p>Is there any way to get the specific hooks from theme / plugin?</p>
|
[
{
"answer_id": 240532,
"author": "tivnet",
"author_id": 28961,
"author_profile": "https://wordpress.stackexchange.com/users/28961",
"pm_score": 3,
"selected": true,
"text": "<p>As of 2016-09-25, there is no ideal solution.</p>\n\n<p>The WP-Parser does the job, but you need to set up a special WP site to run it.\nWooCommerce's <code>Hook-docs</code> is something much simpler, and can be easily tweaked.</p>\n\n<p>I just wrote a long comment on the topic here:</p>\n\n<p><a href=\"https://github.com/ApiGen/ApiGen/issues/307#issuecomment-249349187\" rel=\"nofollow\">https://github.com/ApiGen/ApiGen/issues/307#issuecomment-249349187</a></p>\n"
},
{
"answer_id": 348403,
"author": "Ed Rucks",
"author_id": 175227,
"author_profile": "https://wordpress.stackexchange.com/users/175227",
"pm_score": 3,
"selected": false,
"text": "<p>As of 2019-10-16, the ideal solution would be: <a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"noreferrer\">https://wordpress.org/plugins/query-monitor/</a></p>\n\n<p>After installing the plugin, head over to your homepage (or wherever you need to get your list of hooks) and open Query Monitor from the admin bar.</p>\n\n<p>Then, open <strong>Hooks & Action</strong>:\n<a href=\"https://i.stack.imgur.com/KRm47.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/KRm47.png\" alt=\"Hooks & Actions tab in Query Monitor\"></a></p>\n\n<p>You will be able to view all the hooks in action, along with their component (e.g. plugin). You will also be able to filter by component.</p>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52167/"
] |
I want to get the list of all available hooks from active theme / from a specific plugin.
I was tried to get it from global variables `$wp_actions & $wp_filter` But, They are showing all registered hooks.
E.g.
```
global $wp_actions, $wp_filter;
echo '<pre>';
print_r($wp_filter);
```
E.g. If theme or plugin register the action in `after_setup_theme` then it'll list in `[after_setup_theme]` key from `global $wp_filter`.
I was tried one of the best plugin `Simply Show Hooks`. But, It'll also, show all the registered hooks.
Is there any way to get the specific hooks from theme / plugin?
|
As of 2016-09-25, there is no ideal solution.
The WP-Parser does the job, but you need to set up a special WP site to run it.
WooCommerce's `Hook-docs` is something much simpler, and can be easily tweaked.
I just wrote a long comment on the topic here:
<https://github.com/ApiGen/ApiGen/issues/307#issuecomment-249349187>
|
232,056 |
<p>In the attached image, the posts are displayed in a slider style. When I click on post in the slider, suppose CArd5, then the details should of that post eg: the thumbnail, excerpt etc should be displayed in the pop-up, the pop-up html code has been included in the end as " "</p>
<pre><code>Function addcards()
{
$the_query = new WP_Query( array( 'post_type' => 'cards', 'post_status' => 'publish' ));
?>
<body>
<div id="demo">
<div class="container">
<div class="row">
<div class="row">
<div class="span12">
<div id="owl-demo" class="owl-carousel">
<?php
while ($the_query->have_posts())
{
$the_query->the_post();
?>
<div class="item orange">
<!-- <a href = "#modal"> -->
<!-- href = "#modal" -->
<form action="" method = "post">
<a href = "#modal" id="<?php echo get_the_title();?>" onClick="reply_click(this.id)"
class="lbp-inline-link-1 cboxElement" style="text-decoration:none">
<!-- <div style="display: none;">
<div id="lbp-inline-href-1" style="padding:10px; background: #fff;">
<p>This content will be in a popup.</p>
</div>
</div> -->
<div class="squarebox">
<div class="innersquare">
<div>
<table>
<tr>
<td align="left"><p><?php echo get_the_author();?></p></td>
<td align="left"><p><?php echo get_the_date();?></p></td>
</tr>
</table>
</div>
<div>
<h3><?php echo get_the_title();?></h3>
</div>
<div>
<img src="<?php echo the_post_thumbnail_url();?>">
</div>
<div>
<p><?php the_excerpt(); ?></p>
</div>
<div class="fb-share-button" data-href="https://www.facebook.com/Techmatters-125167747841183/" data-layout="button" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.facebook.com%2FTechmatters-125167747841183%2F&amp;src=sdkpreparse">Share</a></div>
<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share" data-url="https://www.facebook.com/Techmatters-125167747841183/"></script>
</div>
</div>
</a>
</form>
<?php $postid = get_the_title(); ?>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function reply_click(clicked_id)
{
var userID = clicked_id;
alert(userID);
}
</script>
<!-- popup html -->
<div class="remodal" data-remodal-id="modal" role="dialog" aria-labelledby="modal1Title" aria-describedby="modal1Desc">
<button data-remodal-action="close" class="remodal-close" aria-label="Close"></button>
<div>
<h2 id="modal1Title" class="results">
</h2>
<p id="modal1Desc">
Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin
with declarative state notation and hash tracking.
</p>
</div>
<br>
<button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
<button data-remodal-action="confirm" class="remodal-confirm">OK</button>
</div>
<?php
}
add_shortcode('cards','addcards');
?>
</code></pre>
<p><a href="https://i.stack.imgur.com/jkPjp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jkPjp.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 232065,
"author": "Neeraj Kumar",
"author_id": 98147,
"author_profile": "https://wordpress.stackexchange.com/users/98147",
"pm_score": -1,
"selected": false,
"text": "<p>there are many ways to this but i suggest ajax for it. When you click on any post get the post_id and pass it to ajax function. Get id in ajax function(in function.php ) you called first and get post data. You can do two things on ajax sucess 1) append complete html( html for popup ) OR 2) just append thumbnail, title,excerpt values in html </p>\n"
},
{
"answer_id": 232353,
"author": "Mr. M",
"author_id": 98200,
"author_profile": "https://wordpress.stackexchange.com/users/98200",
"pm_score": 1,
"selected": false,
"text": "<p>I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.</p>\n\n<pre><code> while ($the_query->have_posts()): $the_query->the_post(); \n\n echo '<div class=\"non-popup\">';\n echo '<div class=\"card-title\" id=\"card-'.get_the_title.'\">'.get_the_title().'</div>';\n write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png) \n echo '</div>';\n echo '<div class=\"popup\" style=\"display:none;\">';\n\n echo '<div class=\"popup-title\">'.get_the_title().'</div>';\n\n write your popup html + code \n\n echo '</div>';\n\nendwhile; \n</code></pre>\n\n<p>Here is the jQuery:</p>\n\n<pre><code> $(document).ready(function(){\n $(\".card-title\").on('click',function(){ \n $(this).siblings().css('display','block'); \n });\n });\n</code></pre>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232056",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97552/"
] |
In the attached image, the posts are displayed in a slider style. When I click on post in the slider, suppose CArd5, then the details should of that post eg: the thumbnail, excerpt etc should be displayed in the pop-up, the pop-up html code has been included in the end as " "
```
Function addcards()
{
$the_query = new WP_Query( array( 'post_type' => 'cards', 'post_status' => 'publish' ));
?>
<body>
<div id="demo">
<div class="container">
<div class="row">
<div class="row">
<div class="span12">
<div id="owl-demo" class="owl-carousel">
<?php
while ($the_query->have_posts())
{
$the_query->the_post();
?>
<div class="item orange">
<!-- <a href = "#modal"> -->
<!-- href = "#modal" -->
<form action="" method = "post">
<a href = "#modal" id="<?php echo get_the_title();?>" onClick="reply_click(this.id)"
class="lbp-inline-link-1 cboxElement" style="text-decoration:none">
<!-- <div style="display: none;">
<div id="lbp-inline-href-1" style="padding:10px; background: #fff;">
<p>This content will be in a popup.</p>
</div>
</div> -->
<div class="squarebox">
<div class="innersquare">
<div>
<table>
<tr>
<td align="left"><p><?php echo get_the_author();?></p></td>
<td align="left"><p><?php echo get_the_date();?></p></td>
</tr>
</table>
</div>
<div>
<h3><?php echo get_the_title();?></h3>
</div>
<div>
<img src="<?php echo the_post_thumbnail_url();?>">
</div>
<div>
<p><?php the_excerpt(); ?></p>
</div>
<div class="fb-share-button" data-href="https://www.facebook.com/Techmatters-125167747841183/" data-layout="button" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.facebook.com%2FTechmatters-125167747841183%2F&src=sdkpreparse">Share</a></div>
<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share" data-url="https://www.facebook.com/Techmatters-125167747841183/"></script>
</div>
</div>
</a>
</form>
<?php $postid = get_the_title(); ?>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function reply_click(clicked_id)
{
var userID = clicked_id;
alert(userID);
}
</script>
<!-- popup html -->
<div class="remodal" data-remodal-id="modal" role="dialog" aria-labelledby="modal1Title" aria-describedby="modal1Desc">
<button data-remodal-action="close" class="remodal-close" aria-label="Close"></button>
<div>
<h2 id="modal1Title" class="results">
</h2>
<p id="modal1Desc">
Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin
with declarative state notation and hash tracking.
</p>
</div>
<br>
<button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
<button data-remodal-action="confirm" class="remodal-confirm">OK</button>
</div>
<?php
}
add_shortcode('cards','addcards');
?>
```
[](https://i.stack.imgur.com/jkPjp.png)
|
I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.
```
while ($the_query->have_posts()): $the_query->the_post();
echo '<div class="non-popup">';
echo '<div class="card-title" id="card-'.get_the_title.'">'.get_the_title().'</div>';
write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png)
echo '</div>';
echo '<div class="popup" style="display:none;">';
echo '<div class="popup-title">'.get_the_title().'</div>';
write your popup html + code
echo '</div>';
endwhile;
```
Here is the jQuery:
```
$(document).ready(function(){
$(".card-title").on('click',function(){
$(this).siblings().css('display','block');
});
});
```
|
232,080 |
<p>We have user profile page in frontend. We need to add functionality to user add their profile image from profile page in frontend. </p>
<p>Is any plugin or custom functions available for that ? </p>
|
[
{
"answer_id": 232065,
"author": "Neeraj Kumar",
"author_id": 98147,
"author_profile": "https://wordpress.stackexchange.com/users/98147",
"pm_score": -1,
"selected": false,
"text": "<p>there are many ways to this but i suggest ajax for it. When you click on any post get the post_id and pass it to ajax function. Get id in ajax function(in function.php ) you called first and get post data. You can do two things on ajax sucess 1) append complete html( html for popup ) OR 2) just append thumbnail, title,excerpt values in html </p>\n"
},
{
"answer_id": 232353,
"author": "Mr. M",
"author_id": 98200,
"author_profile": "https://wordpress.stackexchange.com/users/98200",
"pm_score": 1,
"selected": false,
"text": "<p>I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.</p>\n\n<pre><code> while ($the_query->have_posts()): $the_query->the_post(); \n\n echo '<div class=\"non-popup\">';\n echo '<div class=\"card-title\" id=\"card-'.get_the_title.'\">'.get_the_title().'</div>';\n write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png) \n echo '</div>';\n echo '<div class=\"popup\" style=\"display:none;\">';\n\n echo '<div class=\"popup-title\">'.get_the_title().'</div>';\n\n write your popup html + code \n\n echo '</div>';\n\nendwhile; \n</code></pre>\n\n<p>Here is the jQuery:</p>\n\n<pre><code> $(document).ready(function(){\n $(\".card-title\").on('click',function(){ \n $(this).siblings().css('display','block'); \n });\n });\n</code></pre>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98209/"
] |
We have user profile page in frontend. We need to add functionality to user add their profile image from profile page in frontend.
Is any plugin or custom functions available for that ?
|
I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.
```
while ($the_query->have_posts()): $the_query->the_post();
echo '<div class="non-popup">';
echo '<div class="card-title" id="card-'.get_the_title.'">'.get_the_title().'</div>';
write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png)
echo '</div>';
echo '<div class="popup" style="display:none;">';
echo '<div class="popup-title">'.get_the_title().'</div>';
write your popup html + code
echo '</div>';
endwhile;
```
Here is the jQuery:
```
$(document).ready(function(){
$(".card-title").on('click',function(){
$(this).siblings().css('display','block');
});
});
```
|
232,091 |
<p>I recently started wp development and am trying to make a website on the Wonderflux framework. </p>
<p>Currently, I set the homepage as a static page from the WP admin dashboard. Now I am currently editing said page inside wp.</p>
<p><a href="https://i.stack.imgur.com/O9yza.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9yza.png" alt="wp edit"></a></p>
<p>Is this the correct way to do this? Is there a way to simply redirect to <code>custom-home.php</code> on page load? Where that file would load the header, page content and the footer. </p>
<p>I am going to be having multiple pages with each their own looks so I think this should be accomplished using functions.php in my child theme but I'm not sure where to start. I just want WP to mainly handle pages with posts/blog content.</p>
<p>I apologize if I sound a bit scattered, I don't think using a framework for my first WP project was a good idea. I'm used to bootstrap and was looking for a similar environment to build a responsive website. I feel like the only way I can properly learn everything is to build a theme from the ground up using the codex, but I don't have that much time unfortunately.</p>
<p>Any guidance would greatly be appreciated. </p>
|
[
{
"answer_id": 232065,
"author": "Neeraj Kumar",
"author_id": 98147,
"author_profile": "https://wordpress.stackexchange.com/users/98147",
"pm_score": -1,
"selected": false,
"text": "<p>there are many ways to this but i suggest ajax for it. When you click on any post get the post_id and pass it to ajax function. Get id in ajax function(in function.php ) you called first and get post data. You can do two things on ajax sucess 1) append complete html( html for popup ) OR 2) just append thumbnail, title,excerpt values in html </p>\n"
},
{
"answer_id": 232353,
"author": "Mr. M",
"author_id": 98200,
"author_profile": "https://wordpress.stackexchange.com/users/98200",
"pm_score": 1,
"selected": false,
"text": "<p>I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.</p>\n\n<pre><code> while ($the_query->have_posts()): $the_query->the_post(); \n\n echo '<div class=\"non-popup\">';\n echo '<div class=\"card-title\" id=\"card-'.get_the_title.'\">'.get_the_title().'</div>';\n write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png) \n echo '</div>';\n echo '<div class=\"popup\" style=\"display:none;\">';\n\n echo '<div class=\"popup-title\">'.get_the_title().'</div>';\n\n write your popup html + code \n\n echo '</div>';\n\nendwhile; \n</code></pre>\n\n<p>Here is the jQuery:</p>\n\n<pre><code> $(document).ready(function(){\n $(\".card-title\").on('click',function(){ \n $(this).siblings().css('display','block'); \n });\n });\n</code></pre>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232091",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98213/"
] |
I recently started wp development and am trying to make a website on the Wonderflux framework.
Currently, I set the homepage as a static page from the WP admin dashboard. Now I am currently editing said page inside wp.
[](https://i.stack.imgur.com/O9yza.png)
Is this the correct way to do this? Is there a way to simply redirect to `custom-home.php` on page load? Where that file would load the header, page content and the footer.
I am going to be having multiple pages with each their own looks so I think this should be accomplished using functions.php in my child theme but I'm not sure where to start. I just want WP to mainly handle pages with posts/blog content.
I apologize if I sound a bit scattered, I don't think using a framework for my first WP project was a good idea. I'm used to bootstrap and was looking for a similar environment to build a responsive website. I feel like the only way I can properly learn everything is to build a theme from the ground up using the codex, but I don't have that much time unfortunately.
Any guidance would greatly be appreciated.
|
I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.
```
while ($the_query->have_posts()): $the_query->the_post();
echo '<div class="non-popup">';
echo '<div class="card-title" id="card-'.get_the_title.'">'.get_the_title().'</div>';
write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png)
echo '</div>';
echo '<div class="popup" style="display:none;">';
echo '<div class="popup-title">'.get_the_title().'</div>';
write your popup html + code
echo '</div>';
endwhile;
```
Here is the jQuery:
```
$(document).ready(function(){
$(".card-title").on('click',function(){
$(this).siblings().css('display','block');
});
});
```
|
232,104 |
<p>so I am hoping to retrieve a custom field that is already displayed on the "front-page.php" template on an another page.php template of my website. I know how to do that with the post-id way, but what I'm hoping to do is get it so that it automatically retrieves them from the front page template... the reason why I want to do it that way is because it's a mult-site and I want to re-use the theme installed on sub sites.</p>
<p>So, instead of:</p>
<pre><code> <img src="<?php the_field('image1', 31); ?>" />
</code></pre>
<p>have it be something like:</p>
<pre><code> <img src="<?php the_field('image1', Front Page identifier here); ?>" />
</code></pre>
<p>Can someone please let me know if that's possible? I would really appreciate it!</p>
|
[
{
"answer_id": 232105,
"author": "user319940",
"author_id": 24044,
"author_profile": "https://wordpress.stackexchange.com/users/24044",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$val = get_post_meta( get_the_ID(), 'meta_data_name', true );\necho $val;\n</code></pre>\n\n<p>You can replace get_the_ID() with the ID of the post you are getting the meta from.</p>\n\n<p>You could possible team this with:</p>\n\n<pre><code>$frontpage_id = get_option('page_on_front');\n</code></pre>\n\n<p>to get the homepage ID. Not sure if this would be friendly with multisite though.</p>\n\n<p><code>the_field()</code> is an Advanced Custom Fields function, this can take a second parameter. You can also achieve the same as the above:</p>\n\n<pre><code><?php the_field($field_name, $post_id); ?>\n</code></pre>\n\n<p>replacing post ID with the ID of the post you are retrieving the data from.</p>\n"
},
{
"answer_id": 232294,
"author": "Mixmastermiike",
"author_id": 58060,
"author_profile": "https://wordpress.stackexchange.com/users/58060",
"pm_score": 0,
"selected": false,
"text": "<p>The way I solved this, was to set up a custom post type set up for each of the default images I wanted, then pulled in the post with the featured image associated with each. </p>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58060/"
] |
so I am hoping to retrieve a custom field that is already displayed on the "front-page.php" template on an another page.php template of my website. I know how to do that with the post-id way, but what I'm hoping to do is get it so that it automatically retrieves them from the front page template... the reason why I want to do it that way is because it's a mult-site and I want to re-use the theme installed on sub sites.
So, instead of:
```
<img src="<?php the_field('image1', 31); ?>" />
```
have it be something like:
```
<img src="<?php the_field('image1', Front Page identifier here); ?>" />
```
Can someone please let me know if that's possible? I would really appreciate it!
|
```
$val = get_post_meta( get_the_ID(), 'meta_data_name', true );
echo $val;
```
You can replace get\_the\_ID() with the ID of the post you are getting the meta from.
You could possible team this with:
```
$frontpage_id = get_option('page_on_front');
```
to get the homepage ID. Not sure if this would be friendly with multisite though.
`the_field()` is an Advanced Custom Fields function, this can take a second parameter. You can also achieve the same as the above:
```
<?php the_field($field_name, $post_id); ?>
```
replacing post ID with the ID of the post you are retrieving the data from.
|
232,115 |
<p>I am in the process of rewriting a lot of my code and restructuring a lot of my theme files to use template parts (i.e. using <code>get_template_part()</code>). I've come upon a situation where I want to use the same template parts whether I'm using the main query or a secondary custom query (using <code>WP_Query</code>). The template parts also use core functions that rely on the main query (such as conditionals).</p>
<p>I can get around the problem by overwriting the main query (or overwriting the <code>$wp_query</code> global which holds the main query, the main query still exists) with my custom query and resetting the main query once I'm done. This also means I can use the same loop for the main query and my custom queries. For example:</p>
<pre><code>// Query
if ( $i_need_a_custom_query ) {
$wp_query = new WP_Query($custom_query_args);
}
// The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Do some loop stuff
// and call some functions that rely on the main query
// End the loop
endwhile; endif;
// I'm done so reset the query
wp_reset_query();
</code></pre>
<p>This works. No problem at all, but it seems a bit of a hack to me. So my question is:</p>
<ul>
<li>Am I right to be weary of overwriting the main query like this?</li>
<li>Are there any side effects I'm missing?</li>
<li>And am I correct in assuming that calling <code>wp_reset_query()</code> isn't costly (i.e. it isn't actually re-running the query but simply resetting the globals which are still around somewhere)?</li>
</ul>
<p>Edit to clarify:</p>
<p>I am only using the custom queries in question as secondary queries, that's the whole point of the question. I want to use the same template wether I am using a custom <em>secondary</em> query or using the main query. I understand that what I am doing is essentially the same as using <code>query_posts()</code>, which is a bad idea. As far as I'm aware and broadly speaking, the 2 drawbacks to using <code>query_posts()</code> are 1. Performance, which isn't an issue because I am only doing this when running a secondary custom query anyway and 2. Unintended consequences from changing the global $wp_query, which is exactly what I <em>do</em> want to happen (and as I said is actually working perfectly).</p>
|
[
{
"answer_id": 232117,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>I feel like you should be using <code>get_template_part()</code> for markup. Let's say you have a Custom Template and the Blog which uses the same <code>get_template_part()</code>. You would call the template_part <em>in</em> the loop instead of calling The Loop in the part. For example:</p>\n\n<p><strong>Your Custom Template</strong></p>\n\n<pre><code>$custom_query = new WP_Query( $args );\n\nif ( $custom_query->have_posts() ) {\n while ( $custom_query->have_posts() ) { \n $custom_query->the_post();\n get_template_part( $path );\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<p><strong>Your Blog File</strong></p>\n\n<pre><code>if ( have_posts() ) {\n while ( have_posts() ) { \n the_post();\n get_template_part( $path );\n }\n}\n</code></pre>\n\n<p>This will give both your custom template and your Blog File access to variables like <code>the_title()</code> and <code>the_permamlink()</code> without necessarily having to overwrite the main query. In the end, the above will give you more flexibility.</p>\n\n<hr>\n\n<p>Overwriting the Main Query is <em>almost</em> always a bad idea and will become a headache later. The <code>wp_reset_query()</code> function isn't the biggest overhead but it still does more than really necessary when dealing with secondary queries. If we look at the <a href=\"https://developer.wordpress.org/reference/functions/wp_reset_query/\" rel=\"nofollow\">function itself</a> it pretty much resets a few more globals and calls the <code>wp_reset_postdata()</code> function which we could just call ourselves instead.</p>\n"
},
{
"answer_id": 232141,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 0,
"selected": false,
"text": "<p>What you are doing is exactly to a T what <code>query_posts</code> does, and it really is a bad idea. To prove my point, here is the sorce code for <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow\"><code>query_posts()</code></a></p>\n\n<pre><code>function query_posts($query) {\n $GLOBALS['wp_query'] = new WP_Query();\n return $GLOBALS['wp_query']->query($query);\n}\n</code></pre>\n\n<p>Remember, <code>$GLOBALS['wp_query'] === $wp_query</code>. Now, look at your code, and you'll find it is the same.</p>\n\n<p>There are more than enough writing about just how bad <code>query_posts</code> is, so take your time and work throught them. </p>\n\n<p>There is never a valid reason to replace the main query on any page. Replacing the main query will <strong>ALWAYS</strong> lead to some issue, it might not be visible immediatly, but you'll definitely see the effect of it. </p>\n\n<p>You'll also have to remember, if you are after SEO and performance, then the really bad news is that you definitely are doing it wrong then. The main query always runs normally on any page load, ie, it will query the db and return the relevant posts for the page. Simply removing the loop does <strong>NOT</strong> stop the main query. If you replace the loop with a custom one, as in your example, you are again querying the db, which means you are doing twice as much queries and also slowing the page down due to that. This negatively affect SEO, so there is something for you to think about.</p>\n\n<p>To conclude, if you need something else from the main query, <strong>ALWAYS</strong> use <code>pre_get_posts</code> to alter it. This way you are not running any extra queries or breaking globals</p>\n"
},
{
"answer_id": 232673,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>In general, I agree with Howdy_McGee that one should avoid overwriting the main query unless absolutely necessary - more often than not, modifying the main query with something like a <code>'pre_get_posts'</code> hook is a better solution to such scenarios.</p>\n\n<p>Manually overwriting the global <code>$wp_query</code> can cause all sorts of unintended behaviors if you are not exceedingly careful, including breaking pagination, among other things. It is, in essence, an even more simplistic equivalent to the often criticized <code>query_posts()</code> function, which <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow\">the WordPress Code Reference notes</a>:</p>\n\n<blockquote>\n <p>This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible. In most cases, there are better, more performant options for modifying the main query such as via the ‘pre_get_posts’ action within WP_Query.</p>\n</blockquote>\n\n<p>In this instance however, where you require either:</p>\n\n<ul>\n<li>Simultaneous access to both the main query as well as a secondary query for their distinct content and/or <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">conditional tags</a></li>\n<li>A generic implementation in something like a reusable template part that can be applied to either the main query or any custom query</li>\n</ul>\n\n<p>then one solution is to store the \"contextual\" <code>WP_Query</code> instance in a local variable, and invoke <code>WP_Query</code>'s conditional methods on that variable instead of using their globally-available conditional tag function counterparts (which always explicitly reference the main query, <code>global $wp_query</code>).</p>\n\n<p>For instance, if you wanted your \"contextual query variable\" to refer to a custom secondary query in single and archive templates for your custom post type, <code>my-custom-post-type</code>, but refer to the main query in every other case, you could do the following:</p>\n\n<p><strong>Theme's <code>functions.php</code> file, or a plugin file:</strong></p>\n\n<pre><code>function wpse_232115_get_contextual_query() {\n global $wp_query;\n static $contextual_query;\n\n // A convenient means to check numerous conditionals without a bunch of '||' operations,\n // i.e \"if( $i_need_a_custom_query )\"\n if( in_array( true,\n [\n is_singular( 'my-custom-post-type' ),\n is_post_type_archive( 'my-custom-post-type' )\n ]\n ) ) {\n // Create the contextual query instance, if it doesn't yet exist\n if( ! isset( $contextual_query ) ) {\n $query_args = [\n //...\n ];\n\n $contextual_query = new WP_Query( $query_args );\n }\n\n return $contextual_query;\n }\n\n return $wp_query;\n}\n</code></pre>\n\n<p><strong>\"Generic\" template-part files:</strong></p>\n\n<pre><code>$query = wpse_232115_get_contextual_query();\n\n// Contextual Query loop (loops through your custom query when 'my-custom-post-type's\n// are being displayed, the main $wp_query otherwise.\nif ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();\n // Tags dependent on The Loop will refer to the contextual query if The Loop\n // was set up with the \"$query->\" prefix, as above. Without it, they always\n // refer to the main query.\n the_title();\n\n // The global conditional tags always refer to the main query\n if( is_singular() ) {\n //... Do stuff is the main query result is_singular();\n }\n\n // Conditional methods on the $query object reference describe either\n // the main query, or a custom query depending on the context.\n if( $query->is_archive() ) {\n //... Do stuff if the $query query result is an archive\n }\n// End the loop\nendwhile; endif;\n</code></pre>\n\n<p>I'm not sure if this is the best solution, but it's how I would think to approach the problem.</p>\n"
}
] |
2016/07/12
|
[
"https://wordpress.stackexchange.com/questions/232115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81652/"
] |
I am in the process of rewriting a lot of my code and restructuring a lot of my theme files to use template parts (i.e. using `get_template_part()`). I've come upon a situation where I want to use the same template parts whether I'm using the main query or a secondary custom query (using `WP_Query`). The template parts also use core functions that rely on the main query (such as conditionals).
I can get around the problem by overwriting the main query (or overwriting the `$wp_query` global which holds the main query, the main query still exists) with my custom query and resetting the main query once I'm done. This also means I can use the same loop for the main query and my custom queries. For example:
```
// Query
if ( $i_need_a_custom_query ) {
$wp_query = new WP_Query($custom_query_args);
}
// The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Do some loop stuff
// and call some functions that rely on the main query
// End the loop
endwhile; endif;
// I'm done so reset the query
wp_reset_query();
```
This works. No problem at all, but it seems a bit of a hack to me. So my question is:
* Am I right to be weary of overwriting the main query like this?
* Are there any side effects I'm missing?
* And am I correct in assuming that calling `wp_reset_query()` isn't costly (i.e. it isn't actually re-running the query but simply resetting the globals which are still around somewhere)?
Edit to clarify:
I am only using the custom queries in question as secondary queries, that's the whole point of the question. I want to use the same template wether I am using a custom *secondary* query or using the main query. I understand that what I am doing is essentially the same as using `query_posts()`, which is a bad idea. As far as I'm aware and broadly speaking, the 2 drawbacks to using `query_posts()` are 1. Performance, which isn't an issue because I am only doing this when running a secondary custom query anyway and 2. Unintended consequences from changing the global $wp\_query, which is exactly what I *do* want to happen (and as I said is actually working perfectly).
|
In general, I agree with Howdy\_McGee that one should avoid overwriting the main query unless absolutely necessary - more often than not, modifying the main query with something like a `'pre_get_posts'` hook is a better solution to such scenarios.
Manually overwriting the global `$wp_query` can cause all sorts of unintended behaviors if you are not exceedingly careful, including breaking pagination, among other things. It is, in essence, an even more simplistic equivalent to the often criticized `query_posts()` function, which [the WordPress Code Reference notes](https://developer.wordpress.org/reference/functions/query_posts/):
>
> This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible. In most cases, there are better, more performant options for modifying the main query such as via the ‘pre\_get\_posts’ action within WP\_Query.
>
>
>
In this instance however, where you require either:
* Simultaneous access to both the main query as well as a secondary query for their distinct content and/or [conditional tags](https://codex.wordpress.org/Conditional_Tags)
* A generic implementation in something like a reusable template part that can be applied to either the main query or any custom query
then one solution is to store the "contextual" `WP_Query` instance in a local variable, and invoke `WP_Query`'s conditional methods on that variable instead of using their globally-available conditional tag function counterparts (which always explicitly reference the main query, `global $wp_query`).
For instance, if you wanted your "contextual query variable" to refer to a custom secondary query in single and archive templates for your custom post type, `my-custom-post-type`, but refer to the main query in every other case, you could do the following:
**Theme's `functions.php` file, or a plugin file:**
```
function wpse_232115_get_contextual_query() {
global $wp_query;
static $contextual_query;
// A convenient means to check numerous conditionals without a bunch of '||' operations,
// i.e "if( $i_need_a_custom_query )"
if( in_array( true,
[
is_singular( 'my-custom-post-type' ),
is_post_type_archive( 'my-custom-post-type' )
]
) ) {
// Create the contextual query instance, if it doesn't yet exist
if( ! isset( $contextual_query ) ) {
$query_args = [
//...
];
$contextual_query = new WP_Query( $query_args );
}
return $contextual_query;
}
return $wp_query;
}
```
**"Generic" template-part files:**
```
$query = wpse_232115_get_contextual_query();
// Contextual Query loop (loops through your custom query when 'my-custom-post-type's
// are being displayed, the main $wp_query otherwise.
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
// Tags dependent on The Loop will refer to the contextual query if The Loop
// was set up with the "$query->" prefix, as above. Without it, they always
// refer to the main query.
the_title();
// The global conditional tags always refer to the main query
if( is_singular() ) {
//... Do stuff is the main query result is_singular();
}
// Conditional methods on the $query object reference describe either
// the main query, or a custom query depending on the context.
if( $query->is_archive() ) {
//... Do stuff if the $query query result is an archive
}
// End the loop
endwhile; endif;
```
I'm not sure if this is the best solution, but it's how I would think to approach the problem.
|
232,127 |
<p>I have been trying to make a sign-out plugin that allows users to sign out from military training activities that they should be at. After they fill out a form explaining why they are not going to be at an activity, they submit it, and it puts all the data into a mysql database. I am trying to save the user's id to their other data so we can tell who is signing out, but everything I have tried breaks the plugin, and gives me the white screen of death.</p>
<p>Thanks for your help. Here is my code to get the users id:</p>
<pre><code>function f2user() {
// Get the current user's info
$current_user = wp_get_current_user();
if ( !($current_user instanceof WP_User) )
return;
return $current_user->ID;
}
$usersid = f2user();
$activity = $_POST['activity'];
$reason = $_POST['reason'];
$explanation = $_POST['explanation'];
</code></pre>
|
[
{
"answer_id": 232128,
"author": "Ehsaan",
"author_id": 54782,
"author_profile": "https://wordpress.stackexchange.com/users/54782",
"pm_score": 0,
"selected": false,
"text": "<p>You can get current user ID easily using <code>get_current_user_id()</code>.</p>\n\n<pre><code>$usersid = get_current_user_id();\n$activity = $_POST['activity'];\n$reason = $_POST['reason'];\n$explanation = $_POST['explanation'];\n</code></pre>\n\n<p>For your function <code>f2user()</code> you can change your code to this:</p>\n\n<pre><code>$current_user = wp_get_current_user(); \nreturn $current_user->ID;\n</code></pre>\n\n<p>According to <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow\"><code>wp_get_current_user()</code> doc</a>, if no user is signed in, <code>$current_user->ID</code> would return 0.</p>\n"
},
{
"answer_id": 276190,
"author": "Rahul Parikh",
"author_id": 125461,
"author_profile": "https://wordpress.stackexchange.com/users/125461",
"pm_score": 1,
"selected": false,
"text": "<p>Try this.\nIf no user are signed in then wp_get_current_user get fatal error so your plugin breaks. But if you want only user id then use get_current_user_id.\nIf no user signed in then it will return 0. So your plugin will not break.\nThanks</p>\n\n<pre><code>function f2user() {\n // Get the current user's info \n $current_user = get_current_user_id(); \n return $current_user;\n}\n$usersid = f2user();\n</code></pre>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98239/"
] |
I have been trying to make a sign-out plugin that allows users to sign out from military training activities that they should be at. After they fill out a form explaining why they are not going to be at an activity, they submit it, and it puts all the data into a mysql database. I am trying to save the user's id to their other data so we can tell who is signing out, but everything I have tried breaks the plugin, and gives me the white screen of death.
Thanks for your help. Here is my code to get the users id:
```
function f2user() {
// Get the current user's info
$current_user = wp_get_current_user();
if ( !($current_user instanceof WP_User) )
return;
return $current_user->ID;
}
$usersid = f2user();
$activity = $_POST['activity'];
$reason = $_POST['reason'];
$explanation = $_POST['explanation'];
```
|
Try this.
If no user are signed in then wp\_get\_current\_user get fatal error so your plugin breaks. But if you want only user id then use get\_current\_user\_id.
If no user signed in then it will return 0. So your plugin will not break.
Thanks
```
function f2user() {
// Get the current user's info
$current_user = get_current_user_id();
return $current_user;
}
$usersid = f2user();
```
|
232,135 |
<p>I am new to word press but know all the required PHP skills.
I am using a form to create session in one page and then accessing those sessions in another page. I have done this already without word press. What i need is someone tells me how to do this in word press. what files i have to change in word press, which code i should enter in which file ?</p>
<p><strong>The main part is i am using google-map-api to calculate the distance between two locations</strong></p>
<p>here is my code so far:<br>
<strong>22.php file :</strong> </p>
<pre><code><?php
session_start();
$pickup = '';
$pickupadd = '';
$dropoff = '';
$dropoffadd = '';
$km = '';
$_SESSION['pickup'] = $pickup;
$_SESSION['pickupadd'] = $pickupadd;
$_SESSION['dropoff'] = $dropoff;
$_SESSION['dropoffadd'] = $dropoffadd;
$_SESSION['km'] = $km;
?>
<form class="uk-form" action="1111.php" method="get"><label style="color:
#0095da;"> Pick UP</label>
<input id="pickup" name="pickup" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Pick UP location" />
<input id="pickup_address" name="pickupadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Drop OFF</label>
<input id="dropoff" name="dropoff" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Drop OFF location" />
<input id="dropoff_address" name="dropoffadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Pickup Time</label>
<input id="km" name="km" class="controls" type="hidden" value="" />
<input type="submit" />
</form>
</code></pre>
<p><strong>1111.php file :</strong> </p>
<pre><code> <?php
session_start();
$pickup = $_SESSION['pickup'] ;
$pickupadd = $_SESSION['pickupadd'] ;
$dropoff = $_SESSION['dropoff'] ;
$dropoffadd = $_SESSION['dropoffadd'] ;
$km = $_SESSION['km'] ;
if (isset($_GET["pickup"]) || isset($_GET["pickupadd"]) ||
isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])
) {
$_SESSION["pickup"] = $_GET["pickup"];
$_SESSION["pickupadd"] = $_GET["pickupadd"];
$_SESSION["dropoff"] = $_GET["dropoff"];
$_SESSION["dropoffadd"] = $_GET["dropoffadd"];
$_SESSION["km"] = $_GET["km"];
}
?>
<body>
<?php
echo $_SESSION["pickup"];
echo $_SESSION["pickupadd"];
echo $_SESSION["dropoff"];
echo $_SESSION["dropoffadd"];
echo $_SESSION["km"];
?>
</body>
</code></pre>
|
[
{
"answer_id": 232137,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 1,
"selected": false,
"text": "<p>You want to use the init hook to start the session such as:</p>\n\n<pre><code>function start_session() {\n if(!session_id()) {\n session_start();\n }\n}\n\nadd_action('init', 'start_session', 1);\n\nfunction end_session() {\n session_destroy ();\n}\n\nadd_action('wp_logout', 'end_session');\nadd_action('wp_login', 'end_session');\n</code></pre>\n\n<p>This would go in the functions.php file.</p>\n\n<p>I suggest you have a look here for more info:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Hooks</a></p>\n"
},
{
"answer_id": 232151,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>TomC is right, but to build on that here's what I do. Mainly I use this with a global object which I serialise into the session to save and unserialise from the session to use. Here I've just used an array of your variables. This way you don't need to worry about saving into the session as you go and the session use is easily expanded for other data.</p>\n\n<p>My main use is for shopping baskets and orders, so <strong>proper sanitisation, validation and nonces are important</strong>, but they are left out here to keep the examples clean. See <a href=\"https://developer.wordpress.org/plugins/security/nonces/\" rel=\"nofollow\">https://developer.wordpress.org/plugins/security/nonces/</a> and <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow\">https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data</a></p>\n\n<p>Assuming this is all going into your theme, you have init code similar to TomC's in <code>functions.php</code></p>\n\n<pre><code>add_action( 'init', 'setup_session' );\n\nfunction setup_session() {\n\n session_start();\n global $map_data;\n\n if (isset($_SESSION['map_data'])) {\n $map_data = unserialize($_SESSION['map_data']);\n } else {\n $map_data = array(); \n }\n\n process_get();\n /* chain it after session setup, but could also hook into\n init with a lower priority so that $_GET always writes\n over older session data, or put your own action here to\n give multiple functions access to your sessions\n */\n}\n\nadd_action( 'shutdown', 'save_session' ); \n\nfunction save_session() {\n\n global $map_data;\n if (isset($map_data)) {\n $_SESSION['map_data'] = serialize($map_data);\n }\n\n}\n\nfunction process_get() {\n\n // do modify this to:\n // check nonce\n // sanitise\n // validate\n\n` global $map_data;\n\n if ( isset($_GET[\"pickup\"]) || isset($_GET[\"pickupadd\"]) || isset($_GET[\"dropoff\"]) || isset($_GET[\"dropoffadd\"]) || isset($_GET[\"km\"]) \n ) {\n $map_data[\"pickup\"] = $_GET[\"pickup\"];\n $map_data[\"pickupadd\"] = $_GET[\"pickupadd\"];\n $map_data[\"dropoff\"] = $_GET[\"dropoff\"];\n $map_data[\"dropoffadd\"] = $_GET[\"dropoffadd\"];\n $map_data[\"km\"] = $_GET[\"km\"];\n}\n// if any of these $_GET vars is set, replace the whole array\n\n\n}\n</code></pre>\n\n<p>You're also right that this could go into your template files as long as you start your session before PHP sends out the headers. In a well written theme (and assuming you aren't running any poorly written plugins) anywhere before your HTML tag will work. Hooking into WP actions is a bit more robust in this regard, but putting the $_GET processing into a template would let you easily keep it to one page instead of running it on all of them.</p>\n\n<p>You can go a step further, though this may be more effort than you need in your case, and use custom session code: <a href=\"https://pippinsplugins.com/storing-session-data-in-wordpress-without-_session/\" rel=\"nofollow\">https://pippinsplugins.com/storing-session-data-in-wordpress-without-_session/</a></p>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98132/"
] |
I am new to word press but know all the required PHP skills.
I am using a form to create session in one page and then accessing those sessions in another page. I have done this already without word press. What i need is someone tells me how to do this in word press. what files i have to change in word press, which code i should enter in which file ?
**The main part is i am using google-map-api to calculate the distance between two locations**
here is my code so far:
**22.php file :**
```
<?php
session_start();
$pickup = '';
$pickupadd = '';
$dropoff = '';
$dropoffadd = '';
$km = '';
$_SESSION['pickup'] = $pickup;
$_SESSION['pickupadd'] = $pickupadd;
$_SESSION['dropoff'] = $dropoff;
$_SESSION['dropoffadd'] = $dropoffadd;
$_SESSION['km'] = $km;
?>
<form class="uk-form" action="1111.php" method="get"><label style="color:
#0095da;"> Pick UP</label>
<input id="pickup" name="pickup" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Pick UP location" />
<input id="pickup_address" name="pickupadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Drop OFF</label>
<input id="dropoff" name="dropoff" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Drop OFF location" />
<input id="dropoff_address" name="dropoffadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Pickup Time</label>
<input id="km" name="km" class="controls" type="hidden" value="" />
<input type="submit" />
</form>
```
**1111.php file :**
```
<?php
session_start();
$pickup = $_SESSION['pickup'] ;
$pickupadd = $_SESSION['pickupadd'] ;
$dropoff = $_SESSION['dropoff'] ;
$dropoffadd = $_SESSION['dropoffadd'] ;
$km = $_SESSION['km'] ;
if (isset($_GET["pickup"]) || isset($_GET["pickupadd"]) ||
isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])
) {
$_SESSION["pickup"] = $_GET["pickup"];
$_SESSION["pickupadd"] = $_GET["pickupadd"];
$_SESSION["dropoff"] = $_GET["dropoff"];
$_SESSION["dropoffadd"] = $_GET["dropoffadd"];
$_SESSION["km"] = $_GET["km"];
}
?>
<body>
<?php
echo $_SESSION["pickup"];
echo $_SESSION["pickupadd"];
echo $_SESSION["dropoff"];
echo $_SESSION["dropoffadd"];
echo $_SESSION["km"];
?>
</body>
```
|
TomC is right, but to build on that here's what I do. Mainly I use this with a global object which I serialise into the session to save and unserialise from the session to use. Here I've just used an array of your variables. This way you don't need to worry about saving into the session as you go and the session use is easily expanded for other data.
My main use is for shopping baskets and orders, so **proper sanitisation, validation and nonces are important**, but they are left out here to keep the examples clean. See <https://developer.wordpress.org/plugins/security/nonces/> and <https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data>
Assuming this is all going into your theme, you have init code similar to TomC's in `functions.php`
```
add_action( 'init', 'setup_session' );
function setup_session() {
session_start();
global $map_data;
if (isset($_SESSION['map_data'])) {
$map_data = unserialize($_SESSION['map_data']);
} else {
$map_data = array();
}
process_get();
/* chain it after session setup, but could also hook into
init with a lower priority so that $_GET always writes
over older session data, or put your own action here to
give multiple functions access to your sessions
*/
}
add_action( 'shutdown', 'save_session' );
function save_session() {
global $map_data;
if (isset($map_data)) {
$_SESSION['map_data'] = serialize($map_data);
}
}
function process_get() {
// do modify this to:
// check nonce
// sanitise
// validate
` global $map_data;
if ( isset($_GET["pickup"]) || isset($_GET["pickupadd"]) || isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])
) {
$map_data["pickup"] = $_GET["pickup"];
$map_data["pickupadd"] = $_GET["pickupadd"];
$map_data["dropoff"] = $_GET["dropoff"];
$map_data["dropoffadd"] = $_GET["dropoffadd"];
$map_data["km"] = $_GET["km"];
}
// if any of these $_GET vars is set, replace the whole array
}
```
You're also right that this could go into your template files as long as you start your session before PHP sends out the headers. In a well written theme (and assuming you aren't running any poorly written plugins) anywhere before your HTML tag will work. Hooking into WP actions is a bit more robust in this regard, but putting the $\_GET processing into a template would let you easily keep it to one page instead of running it on all of them.
You can go a step further, though this may be more effort than you need in your case, and use custom session code: <https://pippinsplugins.com/storing-session-data-in-wordpress-without-_session/>
|
232,152 |
<p>I have marked the option - " Users must be registered and logged in to comment " in Admin panel Setting -> Discussion section but i want only subscriber role user can comment not other roles type user.</p>
<p>Thanks,</p>
|
[
{
"answer_id": 232154,
"author": "pallavi",
"author_id": 96726,
"author_profile": "https://wordpress.stackexchange.com/users/96726",
"pm_score": 0,
"selected": false,
"text": "<p>The below code check if user is not subscriber then comment form will not display. Comment form only show when user is login and and user role is subscriber.</p>\n\n<pre><code> add_filter( 'init', 'manage_comment');\n\n function manage_comment()\n {\n global $current_user;\n\n $user_roles = $current_user->roles;\n $user_role = array_shift($user_roles);\n if ($user_role!='subscriber')\n { \n add_filter( 'comments_open', '__return_false' );\n } \n }\n</code></pre>\n"
},
{
"answer_id": 232161,
"author": "Tammy Shipps",
"author_id": 98255,
"author_profile": "https://wordpress.stackexchange.com/users/98255",
"pm_score": 1,
"selected": true,
"text": "<p>I suggest adding a snippet to the theme file where the comments form is loaded that checks to make sure there is a logged in user and then, if that user a Subscriber, then show the comments form to them. The examples below use the Twenty Sixteen theme:</p>\n\n<p>In comments.php:</p>\n\n<pre><code>// First, get the current user and check their role\n$user = wp_get_current_user();\nif ( in_array( 'subscriber', (array) $user->roles ) ) {\n // The current user has the subscriber role, show the form\n comment_form( array(\n 'title_reply_before' => '<h2 id=\"reply-title\" class=\"comment-reply-title\">',\n 'title_reply_after' => '</h2>',\n ) );\n}\n</code></pre>\n\n<p>This way, only those users with the subscriber role will see the comments form.</p>\n"
},
{
"answer_id": 232178,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like the first time the core calls <code>wp_get_current_user()</code> is within the <code>WP::init()</code> method. </p>\n\n<p>To better understand the context, we see that it's right after the <code>after_setup_theme</code> hook and just before the <code>init</code> hook <sup><a href=\"https://github.com/WordPress/WordPress/blob/c73c23c423a54fd8592368e234733990e2a64169/wp-settings.php#L392-413\" rel=\"nofollow noreferrer\">src</a></sup>:</p>\n\n<pre><code>do_action( 'after_setup_theme' );\n\n// Set up current user.\n$GLOBALS['wp']->init();\n\ndo_action( 'init' );\n</code></pre>\n\n<p>where <code>WP::init()</code> is defined as <sup><a href=\"https://github.com/WordPress/WordPress/blob/c73c23c423a54fd8592368e234733990e2a64169/wp-includes/class-wp.php#L588-596\" rel=\"nofollow noreferrer\">src</a></sup>:</p>\n\n<pre><code>public function init() {\n wp_get_current_user();\n}\n</code></pre>\n\n<p>The <code>wp_get_current_user()</code> is a wrapper for <code>_wp_get_current_user()</code> that contains calls to <code>wp_set_current_user()</code> in various ways, e.g. with <code>wp_set_current_user(0)</code> for logged-out users.</p>\n\n<p>Here's one suggestion, hook into the <code>set_current_user</code> action within the <code>wp_set_current_user()</code>:</p>\n\n<pre><code>/**\n * Comments only open for users with the 'subscriber' role\n */\nadd_action( 'set_current_user', function() use ( &$current_user )\n{\n if( $current_user instanceof \\WP_User \n && $current_user->exists() \n && in_array( 'subscriber', (array) $current_user->roles, true ) \n )\n return;\n\n add_filter( 'comments_open', '__return_false' );\n\n} );\n</code></pre>\n\n<p>If the current user has the <em>subscriber</em> role then do nothing. For all other users or visitors the comments are forced closed.</p>\n\n<p>I might be too cautious checking for the <code>\\WP_User</code> object instance, but I keep it anyway, as it's possible to mess with the <code>$current_user</code>, as with many other things in WordPress ;-)</p>\n\n<p>The reason for using <code>$current_user</code> here, instead of calling <code>wp_get_current_user()</code>, is to avoid a possible infinite loop, but there are ways to handle that if needed. It's also tempting to play with the <code>determine_current_user</code> filter.</p>\n\n<p>For <em>visitors</em> (not logged in) the <code>wp_get_current_user()</code> will return a <code>\\WP_User</code> object with ID as <code>0</code> and roles as an empty array. That's because of the <code>wp_set_current_user(0)</code> calls mentioned earlier.</p>\n\n<p>Here <code>$current_user->exists()</code> is a wrapper for <code>! empty( $current_user->ID)</code>.</p>\n\n<p>I agree with @TammyShipps regarding the array casting of the roles, but as noted by @cybmeta, only hiding the comment form will not stop other users from being able to comment.</p>\n\n<p>Another approach is a little rewrite of my recent answer <a href=\"https://wordpress.stackexchange.com/a/231921/26350\">here</a>:</p>\n\n<pre><code>/**\n * Comments only open for users with the 'subscriber' role\n */\nadd_action( 'init', function()\n{\n $u = wp_get_current_user();\n\n if( $u->exists() && in_array( 'subscriber', (array) $u->roles, true ) )\n return;\n\n add_filter( 'comments_open', '__return_false' );\n} );\n</code></pre>\n\n<p>Both of these methods should stop direct POST requests to the <code>wp-comments-post.php</code> file, because of the <code>comments_open()</code> check there. I haven't checked but I think it will also work with xml-rpc. </p>\n\n<p>We might also try the <code>pre_comment_on_post</code> hook to stop the comment handling by e.g. throwing an <code>\\WP_Error</code>.</p>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89896/"
] |
I have marked the option - " Users must be registered and logged in to comment " in Admin panel Setting -> Discussion section but i want only subscriber role user can comment not other roles type user.
Thanks,
|
I suggest adding a snippet to the theme file where the comments form is loaded that checks to make sure there is a logged in user and then, if that user a Subscriber, then show the comments form to them. The examples below use the Twenty Sixteen theme:
In comments.php:
```
// First, get the current user and check their role
$user = wp_get_current_user();
if ( in_array( 'subscriber', (array) $user->roles ) ) {
// The current user has the subscriber role, show the form
comment_form( array(
'title_reply_before' => '<h2 id="reply-title" class="comment-reply-title">',
'title_reply_after' => '</h2>',
) );
}
```
This way, only those users with the subscriber role will see the comments form.
|
232,164 |
<p>I have created custom fields on my registration form, such as 'telephone', using <a href="https://wordpress.org/plugins/theme-my-login/" rel="nofollow">Theme My Login</a>. I have found a way to make them appear in the backend (on the User page) but I can't update those fields.</p>
<p>What do I need to do in order to be able to update them?</p>
<p>Register-form.php:</p>
<pre><code><label for="telephone<?php $template->the_instance(); ?>"><?php _e( 'Telephone', 'theme-my-login' ) ?></label>
<input type="text" name="telephone" id="pays<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'telephone' ); ?>"/>
</code></pre>
<p>Functions.php:</p>
<pre><code><?php
function custom_user_profile_fields($user) {
?>
<table class="form-table">
<tr>
<th>
<label for="telephone"><?php _e('Téléphone'); ?></label>
</th>
<td>
<input type="text" name="telephone" id="telephone" value="<?php echo esc_attr( get_the_author_meta( 'telephone', $user->ID ) ); ?>" class="regular-text" />
</td>
</tr>
</table>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');
?>
</code></pre>
|
[
{
"answer_id": 232166,
"author": "shubham jain",
"author_id": 89896,
"author_profile": "https://wordpress.stackexchange.com/users/89896",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following function to update custom field value for user </p>\n\n<pre><code> update_user_meta( $user_id, $meta_key, $meta_value, $prev_value );\n</code></pre>\n\n<p>For more information. Please <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow\">visit</a></p>\n"
},
{
"answer_id": 232449,
"author": "userator",
"author_id": 97014,
"author_profile": "https://wordpress.stackexchange.com/users/97014",
"pm_score": 2,
"selected": true,
"text": "<p>I use <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow\">update_user_meta</a> to update the fields. You can add this in functions.php of your child theme.</p>\n\n<pre><code>function save_extra_user_profile_fields( $user_id ) {\n\nif ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n}\n\nupdate_user_meta( $user_id, 'telephone', $_POST['telephone'] ); \n}\nadd_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n</code></pre>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97014/"
] |
I have created custom fields on my registration form, such as 'telephone', using [Theme My Login](https://wordpress.org/plugins/theme-my-login/). I have found a way to make them appear in the backend (on the User page) but I can't update those fields.
What do I need to do in order to be able to update them?
Register-form.php:
```
<label for="telephone<?php $template->the_instance(); ?>"><?php _e( 'Telephone', 'theme-my-login' ) ?></label>
<input type="text" name="telephone" id="pays<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'telephone' ); ?>"/>
```
Functions.php:
```
<?php
function custom_user_profile_fields($user) {
?>
<table class="form-table">
<tr>
<th>
<label for="telephone"><?php _e('Téléphone'); ?></label>
</th>
<td>
<input type="text" name="telephone" id="telephone" value="<?php echo esc_attr( get_the_author_meta( 'telephone', $user->ID ) ); ?>" class="regular-text" />
</td>
</tr>
</table>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');
?>
```
|
I use [update\_user\_meta](https://codex.wordpress.org/Function_Reference/update_user_meta) to update the fields. You can add this in functions.php of your child theme.
```
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'telephone', $_POST['telephone'] );
}
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
```
|
232,174 |
<p>I need to change default WordPress <code>get_custom_logo()</code> generated url because I need to link to the main multi-site site instead of single site. Is there any filter to change this function?</p>
|
[
{
"answer_id": 232175,
"author": "Davide De Maestri",
"author_id": 8741,
"author_profile": "https://wordpress.stackexchange.com/users/8741",
"pm_score": 3,
"selected": false,
"text": "<p>I solved using this filter:</p>\n\n<pre><code>add_filter( 'get_custom_logo', 'custom_logo_url' );\nfunction custom_logo_url ( $html ) {\n\n$custom_logo_id = get_theme_mod( 'custom_logo' );\n$url = network_site_url();\n$html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( $url ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo',\n ) )\n );\nreturn $html; \n}\n</code></pre>\n"
},
{
"answer_id": 364227,
"author": "Nefeline",
"author_id": 165619,
"author_profile": "https://wordpress.stackexchange.com/users/165619",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an alternative solution:</p>\n\n<pre><code>function update_logo_url( $html ) {\n $site_url = get_site_url();\n\n return str_replace( $site_url, esc_url( 'https://your.url' ), $html );\n}\n\nadd_filter( 'get_custom_logo', 'update_logo_url' );\n</code></pre>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8741/"
] |
I need to change default WordPress `get_custom_logo()` generated url because I need to link to the main multi-site site instead of single site. Is there any filter to change this function?
|
I solved using this filter:
```
add_filter( 'get_custom_logo', 'custom_logo_url' );
function custom_logo_url ( $html ) {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$url = network_site_url();
$html = sprintf( '<a href="%1$s" class="custom-logo-link" rel="home" itemprop="url">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',
) )
);
return $html;
}
```
|
232,185 |
<p>I have a fairly simple AJAX request for my WordPress site. My PHP function is a switch statement and all the other switch statements work except for the recent one I added (change_due_date).</p>
<p>I commented out the majority of the code in my new 'case' to better try to find the problem. </p>
<p>AJAX (at bottom of page, under my other AJAX request (which works)):
</p>
<pre><code> function my_ajax() {
var newDate = <?php echo $new_date; ?>;
var data_string = 'action=do_ajax&fn=change_due_date&newDate=' + newDate;
jQuery.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: data_string,
dataType: 'JSON',
success: function(data){
// alert(data);
console.log("success!");
},
error: function(errorThrown){
console.log("error!");
}
});
} // end of my_ajax function
jQuery('a.test').click(function(){
my_ajax();
});
</script>
</code></pre>
<p>I tried, at first, just sending 'newDate' as my 'data' value - and that did work (as in AJAX returned 'success!'). In that case my PHP function still didn't run, since it wasn't being called. I suspect something is wrong with my formatting on the AJAX side of things... </p>
<p>Now, when I send 'data_string' as my data I get an AJAX error... </p>
<p>PHP Function: </p>
<pre><code>switch($_POST['fn']){ ...
/* AUTOMATE DUE DATE CREATION - made by Alex */
case 'change_due_date' :
/*$field_key = "field_515b2428887d7"; // Key ID for field
$new_date = $_POST['newDate']; // new date
$new_due_date = DateTime::createFromFormat('Ymd', $new_date);
$new_due_date->format('Ymd'); // formatting */
echo ('<h1>functioning</h1>'); // testing purposes
/*$parent_field = get_field($field_key); // Select parent field
foreach($parent_field as $sub_row) :
// Change value of sub-fields
$sub_row['date_due'] = $new_due_date;
$new_values[] = $sub_row; // Load new values into array
endforeach;
update_field( $field_key, $new_values ); // Update ACF*/
$output = "Successfully updated due dates."; // testing
break;
... }
</code></pre>
<p>I've been working on this code for a couple days - I admit I am not the best at AJAX... but I can't seem to find what's wrong? I have looked at the WP Codex for guidance on how to structure my AJAX.</p>
|
[
{
"answer_id": 232219,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>I think you may have a problem in the way you establish your data. If you read the WP Codex on AJAX, you will see the data in the examples is in key/value pairs. That is, the data should look something like this:</p>\n\n<pre><code>var data = {\n 'action' : 'do_ajax',\n 'fn' : 'change_due_date',\n 'newDate' : newDate\n };\n</code></pre>\n\n<p>Also, note the Codex says that the variable <code>ajaxurl</code> points to /wp-admin/admin-ajax.php (since version 2.8). Sometimes, this won't work unless you call <code>wp_localize_script()</code> first.</p>\n\n<p>Personally, I don't use <code>datatype: 'JSON'</code>. I can't say whether or not your scheme is being broken by including it in your data.</p>\n\n<p>Lastly, don't forget this at the end of the PHP function that sends data back to the AJAX call:</p>\n\n<pre><code>echo $output;\nwp_die();\n</code></pre>\n"
},
{
"answer_id": 232233,
"author": "Ronak Dave",
"author_id": 98306,
"author_profile": "https://wordpress.stackexchange.com/users/98306",
"pm_score": 1,
"selected": false,
"text": "<p>A simple answer to your question is that you have the data type as JSON in your ajax request and you are passing a string in it. You need to pass a json object in the ajax request when you chose dataType equals to JSON. A JSON object is typically a key pair value inside curly braces. Here is a reference where you can see how ajax requests can be implemented in WordPress.</p>\n\n<p><a href=\"https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/</a>\n<a href=\"https://stackoverflow.com/questions/14185582/creating-an-ajax-call-in-wordpress-what-do-i-have-to-include-to-access-wordpres\">https://stackoverflow.com/questions/14185582/creating-an-ajax-call-in-wordpress-what-do-i-have-to-include-to-access-wordpres</a></p>\n\n<p>Check the data inside the ajax function. You will need to verify your json before sending it to the server so that there wont be any issues further. Also you will need to decode the json on the PHP server side. Then only you will be able to manipulate the data in your PHP code. May be an alternative way for you is that you can make a request without datatype json and you will get the post values in your PHP code making it easy to use. Check the below link for reference.</p>\n\n<p><a href=\"http://www.makeuseof.com/tag/tutorial-ajax-wordpress/\" rel=\"nofollow noreferrer\">http://www.makeuseof.com/tag/tutorial-ajax-wordpress/</a></p>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97928/"
] |
I have a fairly simple AJAX request for my WordPress site. My PHP function is a switch statement and all the other switch statements work except for the recent one I added (change\_due\_date).
I commented out the majority of the code in my new 'case' to better try to find the problem.
AJAX (at bottom of page, under my other AJAX request (which works)):
```
function my_ajax() {
var newDate = <?php echo $new_date; ?>;
var data_string = 'action=do_ajax&fn=change_due_date&newDate=' + newDate;
jQuery.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: data_string,
dataType: 'JSON',
success: function(data){
// alert(data);
console.log("success!");
},
error: function(errorThrown){
console.log("error!");
}
});
} // end of my_ajax function
jQuery('a.test').click(function(){
my_ajax();
});
</script>
```
I tried, at first, just sending 'newDate' as my 'data' value - and that did work (as in AJAX returned 'success!'). In that case my PHP function still didn't run, since it wasn't being called. I suspect something is wrong with my formatting on the AJAX side of things...
Now, when I send 'data\_string' as my data I get an AJAX error...
PHP Function:
```
switch($_POST['fn']){ ...
/* AUTOMATE DUE DATE CREATION - made by Alex */
case 'change_due_date' :
/*$field_key = "field_515b2428887d7"; // Key ID for field
$new_date = $_POST['newDate']; // new date
$new_due_date = DateTime::createFromFormat('Ymd', $new_date);
$new_due_date->format('Ymd'); // formatting */
echo ('<h1>functioning</h1>'); // testing purposes
/*$parent_field = get_field($field_key); // Select parent field
foreach($parent_field as $sub_row) :
// Change value of sub-fields
$sub_row['date_due'] = $new_due_date;
$new_values[] = $sub_row; // Load new values into array
endforeach;
update_field( $field_key, $new_values ); // Update ACF*/
$output = "Successfully updated due dates."; // testing
break;
... }
```
I've been working on this code for a couple days - I admit I am not the best at AJAX... but I can't seem to find what's wrong? I have looked at the WP Codex for guidance on how to structure my AJAX.
|
A simple answer to your question is that you have the data type as JSON in your ajax request and you are passing a string in it. You need to pass a json object in the ajax request when you chose dataType equals to JSON. A JSON object is typically a key pair value inside curly braces. Here is a reference where you can see how ajax requests can be implemented in WordPress.
<https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/>
<https://stackoverflow.com/questions/14185582/creating-an-ajax-call-in-wordpress-what-do-i-have-to-include-to-access-wordpres>
Check the data inside the ajax function. You will need to verify your json before sending it to the server so that there wont be any issues further. Also you will need to decode the json on the PHP server side. Then only you will be able to manipulate the data in your PHP code. May be an alternative way for you is that you can make a request without datatype json and you will get the post values in your PHP code making it easy to use. Check the below link for reference.
<http://www.makeuseof.com/tag/tutorial-ajax-wordpress/>
|
232,193 |
<p>I have a custom post type called location. I would like to be able to use 2 different templates for this custom post type and select it via the page attributes box. I have a template set up and can select it when I'm editing a Page, but not when I am editing a custom post type. I can't find any information on how to enable this. I want to enable the dropdown select for all the custom post types, not just one.</p>
|
[
{
"answer_id": 232238,
"author": "MrFox",
"author_id": 69240,
"author_profile": "https://wordpress.stackexchange.com/users/69240",
"pm_score": 0,
"selected": false,
"text": "<p>Ok as mmm has pointed out that I can't do the dropdown select of templates on custom post types I have put this code in my single-cpt.php</p>\n\n<pre><code>global $post; \nif ( ( $post->post_type == 'location' ) && has_term( 'news', 'highlights' ) ) { \ninclude('templates/template_feature_highlight_layout.php'); \n}\n</code></pre>\n"
},
{
"answer_id": 299772,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 3,
"selected": false,
"text": "<p>Since WordPress version 4.7 <strong>Post-Type-Templates are enabled</strong> in the WordPress core. </p>\n\n<p>That means that you can <strong>create multiple templates for the single post-type view</strong> as for pages.</p>\n\n<p>For this you just need to edit the single post/type template, and add something like this to the top of the file:</p>\n\n<pre><code>/*\nTemplate Name: Custom Type Template \nTemplate Post Type: post, product, custom-type \n*/\n</code></pre>\n\n<p>On the line <code>Template Post Type</code> you just add your custom post type slug.<br>\nSo this template will be available on the <code>post</code>, <code>product</code> and <code>custom-type</code> post type.</p>\n\n<p>I already answered this <a href=\"https://wordpress.stackexchange.com/a/255021/88895\">here</a>.<br>\nRead more about post-type-templates of WP 4.7 <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"noreferrer\">here</a>.</p>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69240/"
] |
I have a custom post type called location. I would like to be able to use 2 different templates for this custom post type and select it via the page attributes box. I have a template set up and can select it when I'm editing a Page, but not when I am editing a custom post type. I can't find any information on how to enable this. I want to enable the dropdown select for all the custom post types, not just one.
|
Since WordPress version 4.7 **Post-Type-Templates are enabled** in the WordPress core.
That means that you can **create multiple templates for the single post-type view** as for pages.
For this you just need to edit the single post/type template, and add something like this to the top of the file:
```
/*
Template Name: Custom Type Template
Template Post Type: post, product, custom-type
*/
```
On the line `Template Post Type` you just add your custom post type slug.
So this template will be available on the `post`, `product` and `custom-type` post type.
I already answered this [here](https://wordpress.stackexchange.com/a/255021/88895).
Read more about post-type-templates of WP 4.7 [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/).
|
232,201 |
<p>We are developing WordPress with multiple site. We need to share some posts to more than one site. We need to save post in more than one sites with a single click. </p>
<p>I have searched in Google, but I can't get any tutorial for that. </p>
|
[
{
"answer_id": 232238,
"author": "MrFox",
"author_id": 69240,
"author_profile": "https://wordpress.stackexchange.com/users/69240",
"pm_score": 0,
"selected": false,
"text": "<p>Ok as mmm has pointed out that I can't do the dropdown select of templates on custom post types I have put this code in my single-cpt.php</p>\n\n<pre><code>global $post; \nif ( ( $post->post_type == 'location' ) && has_term( 'news', 'highlights' ) ) { \ninclude('templates/template_feature_highlight_layout.php'); \n}\n</code></pre>\n"
},
{
"answer_id": 299772,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 3,
"selected": false,
"text": "<p>Since WordPress version 4.7 <strong>Post-Type-Templates are enabled</strong> in the WordPress core. </p>\n\n<p>That means that you can <strong>create multiple templates for the single post-type view</strong> as for pages.</p>\n\n<p>For this you just need to edit the single post/type template, and add something like this to the top of the file:</p>\n\n<pre><code>/*\nTemplate Name: Custom Type Template \nTemplate Post Type: post, product, custom-type \n*/\n</code></pre>\n\n<p>On the line <code>Template Post Type</code> you just add your custom post type slug.<br>\nSo this template will be available on the <code>post</code>, <code>product</code> and <code>custom-type</code> post type.</p>\n\n<p>I already answered this <a href=\"https://wordpress.stackexchange.com/a/255021/88895\">here</a>.<br>\nRead more about post-type-templates of WP 4.7 <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"noreferrer\">here</a>.</p>\n"
}
] |
2016/07/13
|
[
"https://wordpress.stackexchange.com/questions/232201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98283/"
] |
We are developing WordPress with multiple site. We need to share some posts to more than one site. We need to save post in more than one sites with a single click.
I have searched in Google, but I can't get any tutorial for that.
|
Since WordPress version 4.7 **Post-Type-Templates are enabled** in the WordPress core.
That means that you can **create multiple templates for the single post-type view** as for pages.
For this you just need to edit the single post/type template, and add something like this to the top of the file:
```
/*
Template Name: Custom Type Template
Template Post Type: post, product, custom-type
*/
```
On the line `Template Post Type` you just add your custom post type slug.
So this template will be available on the `post`, `product` and `custom-type` post type.
I already answered this [here](https://wordpress.stackexchange.com/a/255021/88895).
Read more about post-type-templates of WP 4.7 [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/).
|
232,246 |
<p>Clicking the <strong>Update Profile</strong> button in the</p>
<pre><code>[wordpress]/wp-admin/profile.php
</code></pre>
<p>admin screen will allow the user to update his/her profile including the password.</p>
<p>What is the right action hook to use if you want to capture the new password during this password change?</p>
|
[
{
"answer_id": 232300,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>I have been looking around the core files searching for hooks, there were very few when it comes to hooking into <code>edit_user()</code> function which updates the user data in <code>profile.php</code> page, so I have finished with some workarounds:</p>\n\n<p>My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:</p>\n\n<pre><code>add_action(\"check_passwords\", function( $user_login, $pass1, $pass2 ) { \n\n if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )\n return; // not profile.php page, let's mind our business\n\n update_option( \"_se_debug_user_submitted_pass\", wp_get_current_user()->user_pass );\n return;\n\n}, 10, 3);\n\nadd_action(\"admin_init\", function() { \n\n global $pagenow;\n if ( \"profile.php\" !== $pagenow ) return;\n global $current_user;\n\n if ( get_option( $opt_name = \"_se_debug_user_submitted_pass\" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {\n\n // the password has changed.\n echo \"Password has changed!\";\n /* do things here */\n\n delete_option( $opt_name ); // do only once\n }\n\n});\n</code></pre>\n\n<p>That should work and as long as in <code>profile.php</code> page (updating own profile).</p>\n\n<p>To capture the password, after this line:</p>\n\n<p><code>update_option( \"_se_debug_user_submitted_pass\", wp_get_current_user()->user_pass );</code></p>\n\n<p>update a custom option with the new password value <code>$pass2</code> which is the password confirmation, and call this option within <code>// the password has changed.</code> wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.</p>\n\n<p>One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).</p>\n\n<p>Hope that helps somehow.</p>\n"
},
{
"answer_id": 312485,
"author": "dev_masta",
"author_id": 89164,
"author_profile": "https://wordpress.stackexchange.com/users/89164",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes WordPress is running (or it should be running) in sync with some other system, which is my case - users that change their password in WP should have the same new password in one other place - and I need it in plain text at that moment.</p>\n\n<p>The code I used to get the new password, looks a bit cleaner than the previous answer:</p>\n\n<pre><code>// when password is changed from wp-admin (for himself or some other user, if admin)\nfunction update_my_new_password( $user_id ) {\n\n if ( empty( $_POST['pass1'] ) || $_POST['pass1'] !== $_POST['pass2'] ){\n return;\n }\n\n // password changed...\n $new_pass = $_POST['pass1'];\n\n}\nadd_action( 'profile_update', 'update_my_new_password' );\n</code></pre>\n\n<p>The <code>profile_update</code> hook fires on that admin screen from OP and the condition is met if <code>$_POST['pass1']</code> is not empty.\nIt will also fire if the new password is the same as the old password.</p>\n\n<hr>\n\n<p>There is also another case where user can change his password, the lost password feature.\nThe action for that should be <code>after_password_reset</code> or <code>password_reset</code> but I haven't tested that because in my case I need to find the hook for MemberPress plugin which doesn't trigger this particular hook(s).</p>\n"
}
] |
2016/07/14
|
[
"https://wordpress.stackexchange.com/questions/232246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58915/"
] |
Clicking the **Update Profile** button in the
```
[wordpress]/wp-admin/profile.php
```
admin screen will allow the user to update his/her profile including the password.
What is the right action hook to use if you want to capture the new password during this password change?
|
I have been looking around the core files searching for hooks, there were very few when it comes to hooking into `edit_user()` function which updates the user data in `profile.php` page, so I have finished with some workarounds:
My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:
```
add_action("check_passwords", function( $user_login, $pass1, $pass2 ) {
if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )
return; // not profile.php page, let's mind our business
update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );
return;
}, 10, 3);
add_action("admin_init", function() {
global $pagenow;
if ( "profile.php" !== $pagenow ) return;
global $current_user;
if ( get_option( $opt_name = "_se_debug_user_submitted_pass" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {
// the password has changed.
echo "Password has changed!";
/* do things here */
delete_option( $opt_name ); // do only once
}
});
```
That should work and as long as in `profile.php` page (updating own profile).
To capture the password, after this line:
`update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );`
update a custom option with the new password value `$pass2` which is the password confirmation, and call this option within `// the password has changed.` wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.
One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).
Hope that helps somehow.
|
232,249 |
<p>I am new to Wordpress but I have some knowledge of PHP. I am creating a bilingual site (with Polylang) which has many forms. Some of them are handled by Contact Form 7 but some others have to be custom made.</p>
<p>So, the first form I made was quite a disaster - it works but under certain circumstances. </p>
<p>In the archives page of a custom post I insert</p>
<pre><code><form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="post_type" value="myvalue">
<select class="form-control" name="k" id="k">
<?php
for($i=0;$i<2;$i++){?>
<option value="<?php echo $array3[$i]?>"><?php echo $array3[$i];?></option>
<?php }?>
</select>
<span class="input-group-btn">
<button class="btn btn-search" type="submit"><i class="fa fa-search"> </i></button>
</span>
</form>
</code></pre>
<p>I created a template file named mysearchresults.php In there I inserted the essential (between them)</p>
<pre><code> echo $_POST['k'];
echo "Hello world";
</code></pre>
<p>I created a page having as template mysearchresults.php in one language (named mysearchresults) and another in the other language (same template) named mysearchresults-2.</p>
<p>Loading the two pages gives a page with the Hello world printed.</p>
<p>Adding</p>
<pre><code><form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>mysearchresults-2">
</code></pre>
<p>gives 404 (when I press the submit button - having made a selsction) - the same as instead of -2 I put mysearchresults. Putting mysearchresults.php gives the same error.</p>
<p>So I tried another approach, instead of </p>
<pre><code><select class="form-control" name="k" id="k">
</code></pre>
<p>I put </p>
<pre><code><select class="form-control" name="s" id="s">
</code></pre>
<p>and for action I left</p>
<pre><code>action="<?php echo esc_url( home_url( '/' ) ); ?>">
</code></pre>
<p>In the search page I put echo $_POST['s'] and it loads the search results page printing the value of my selection.</p>
<p>What am I doing wrong? How can I have a custom form, pass the values in my action file and make operations on them? Why leaving like this the action label it loads the search results page?</p>
|
[
{
"answer_id": 232300,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>I have been looking around the core files searching for hooks, there were very few when it comes to hooking into <code>edit_user()</code> function which updates the user data in <code>profile.php</code> page, so I have finished with some workarounds:</p>\n\n<p>My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:</p>\n\n<pre><code>add_action(\"check_passwords\", function( $user_login, $pass1, $pass2 ) { \n\n if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )\n return; // not profile.php page, let's mind our business\n\n update_option( \"_se_debug_user_submitted_pass\", wp_get_current_user()->user_pass );\n return;\n\n}, 10, 3);\n\nadd_action(\"admin_init\", function() { \n\n global $pagenow;\n if ( \"profile.php\" !== $pagenow ) return;\n global $current_user;\n\n if ( get_option( $opt_name = \"_se_debug_user_submitted_pass\" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {\n\n // the password has changed.\n echo \"Password has changed!\";\n /* do things here */\n\n delete_option( $opt_name ); // do only once\n }\n\n});\n</code></pre>\n\n<p>That should work and as long as in <code>profile.php</code> page (updating own profile).</p>\n\n<p>To capture the password, after this line:</p>\n\n<p><code>update_option( \"_se_debug_user_submitted_pass\", wp_get_current_user()->user_pass );</code></p>\n\n<p>update a custom option with the new password value <code>$pass2</code> which is the password confirmation, and call this option within <code>// the password has changed.</code> wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.</p>\n\n<p>One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).</p>\n\n<p>Hope that helps somehow.</p>\n"
},
{
"answer_id": 312485,
"author": "dev_masta",
"author_id": 89164,
"author_profile": "https://wordpress.stackexchange.com/users/89164",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes WordPress is running (or it should be running) in sync with some other system, which is my case - users that change their password in WP should have the same new password in one other place - and I need it in plain text at that moment.</p>\n\n<p>The code I used to get the new password, looks a bit cleaner than the previous answer:</p>\n\n<pre><code>// when password is changed from wp-admin (for himself or some other user, if admin)\nfunction update_my_new_password( $user_id ) {\n\n if ( empty( $_POST['pass1'] ) || $_POST['pass1'] !== $_POST['pass2'] ){\n return;\n }\n\n // password changed...\n $new_pass = $_POST['pass1'];\n\n}\nadd_action( 'profile_update', 'update_my_new_password' );\n</code></pre>\n\n<p>The <code>profile_update</code> hook fires on that admin screen from OP and the condition is met if <code>$_POST['pass1']</code> is not empty.\nIt will also fire if the new password is the same as the old password.</p>\n\n<hr>\n\n<p>There is also another case where user can change his password, the lost password feature.\nThe action for that should be <code>after_password_reset</code> or <code>password_reset</code> but I haven't tested that because in my case I need to find the hook for MemberPress plugin which doesn't trigger this particular hook(s).</p>\n"
}
] |
2016/07/14
|
[
"https://wordpress.stackexchange.com/questions/232249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98314/"
] |
I am new to Wordpress but I have some knowledge of PHP. I am creating a bilingual site (with Polylang) which has many forms. Some of them are handled by Contact Form 7 but some others have to be custom made.
So, the first form I made was quite a disaster - it works but under certain circumstances.
In the archives page of a custom post I insert
```
<form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="post_type" value="myvalue">
<select class="form-control" name="k" id="k">
<?php
for($i=0;$i<2;$i++){?>
<option value="<?php echo $array3[$i]?>"><?php echo $array3[$i];?></option>
<?php }?>
</select>
<span class="input-group-btn">
<button class="btn btn-search" type="submit"><i class="fa fa-search"> </i></button>
</span>
</form>
```
I created a template file named mysearchresults.php In there I inserted the essential (between them)
```
echo $_POST['k'];
echo "Hello world";
```
I created a page having as template mysearchresults.php in one language (named mysearchresults) and another in the other language (same template) named mysearchresults-2.
Loading the two pages gives a page with the Hello world printed.
Adding
```
<form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>mysearchresults-2">
```
gives 404 (when I press the submit button - having made a selsction) - the same as instead of -2 I put mysearchresults. Putting mysearchresults.php gives the same error.
So I tried another approach, instead of
```
<select class="form-control" name="k" id="k">
```
I put
```
<select class="form-control" name="s" id="s">
```
and for action I left
```
action="<?php echo esc_url( home_url( '/' ) ); ?>">
```
In the search page I put echo $\_POST['s'] and it loads the search results page printing the value of my selection.
What am I doing wrong? How can I have a custom form, pass the values in my action file and make operations on them? Why leaving like this the action label it loads the search results page?
|
I have been looking around the core files searching for hooks, there were very few when it comes to hooking into `edit_user()` function which updates the user data in `profile.php` page, so I have finished with some workarounds:
My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:
```
add_action("check_passwords", function( $user_login, $pass1, $pass2 ) {
if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )
return; // not profile.php page, let's mind our business
update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );
return;
}, 10, 3);
add_action("admin_init", function() {
global $pagenow;
if ( "profile.php" !== $pagenow ) return;
global $current_user;
if ( get_option( $opt_name = "_se_debug_user_submitted_pass" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {
// the password has changed.
echo "Password has changed!";
/* do things here */
delete_option( $opt_name ); // do only once
}
});
```
That should work and as long as in `profile.php` page (updating own profile).
To capture the password, after this line:
`update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );`
update a custom option with the new password value `$pass2` which is the password confirmation, and call this option within `// the password has changed.` wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.
One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).
Hope that helps somehow.
|
232,254 |
<p><br/>
Is there a way to check that comment was successfully submitted? I want to display some text or hide a comment form for example if comment was succesfully submitted. </p>
|
[
{
"answer_id": 232300,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>I have been looking around the core files searching for hooks, there were very few when it comes to hooking into <code>edit_user()</code> function which updates the user data in <code>profile.php</code> page, so I have finished with some workarounds:</p>\n\n<p>My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:</p>\n\n<pre><code>add_action(\"check_passwords\", function( $user_login, $pass1, $pass2 ) { \n\n if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )\n return; // not profile.php page, let's mind our business\n\n update_option( \"_se_debug_user_submitted_pass\", wp_get_current_user()->user_pass );\n return;\n\n}, 10, 3);\n\nadd_action(\"admin_init\", function() { \n\n global $pagenow;\n if ( \"profile.php\" !== $pagenow ) return;\n global $current_user;\n\n if ( get_option( $opt_name = \"_se_debug_user_submitted_pass\" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {\n\n // the password has changed.\n echo \"Password has changed!\";\n /* do things here */\n\n delete_option( $opt_name ); // do only once\n }\n\n});\n</code></pre>\n\n<p>That should work and as long as in <code>profile.php</code> page (updating own profile).</p>\n\n<p>To capture the password, after this line:</p>\n\n<p><code>update_option( \"_se_debug_user_submitted_pass\", wp_get_current_user()->user_pass );</code></p>\n\n<p>update a custom option with the new password value <code>$pass2</code> which is the password confirmation, and call this option within <code>// the password has changed.</code> wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.</p>\n\n<p>One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).</p>\n\n<p>Hope that helps somehow.</p>\n"
},
{
"answer_id": 312485,
"author": "dev_masta",
"author_id": 89164,
"author_profile": "https://wordpress.stackexchange.com/users/89164",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes WordPress is running (or it should be running) in sync with some other system, which is my case - users that change their password in WP should have the same new password in one other place - and I need it in plain text at that moment.</p>\n\n<p>The code I used to get the new password, looks a bit cleaner than the previous answer:</p>\n\n<pre><code>// when password is changed from wp-admin (for himself or some other user, if admin)\nfunction update_my_new_password( $user_id ) {\n\n if ( empty( $_POST['pass1'] ) || $_POST['pass1'] !== $_POST['pass2'] ){\n return;\n }\n\n // password changed...\n $new_pass = $_POST['pass1'];\n\n}\nadd_action( 'profile_update', 'update_my_new_password' );\n</code></pre>\n\n<p>The <code>profile_update</code> hook fires on that admin screen from OP and the condition is met if <code>$_POST['pass1']</code> is not empty.\nIt will also fire if the new password is the same as the old password.</p>\n\n<hr>\n\n<p>There is also another case where user can change his password, the lost password feature.\nThe action for that should be <code>after_password_reset</code> or <code>password_reset</code> but I haven't tested that because in my case I need to find the hook for MemberPress plugin which doesn't trigger this particular hook(s).</p>\n"
}
] |
2016/07/14
|
[
"https://wordpress.stackexchange.com/questions/232254",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97934/"
] |
Is there a way to check that comment was successfully submitted? I want to display some text or hide a comment form for example if comment was succesfully submitted.
|
I have been looking around the core files searching for hooks, there were very few when it comes to hooking into `edit_user()` function which updates the user data in `profile.php` page, so I have finished with some workarounds:
My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:
```
add_action("check_passwords", function( $user_login, $pass1, $pass2 ) {
if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )
return; // not profile.php page, let's mind our business
update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );
return;
}, 10, 3);
add_action("admin_init", function() {
global $pagenow;
if ( "profile.php" !== $pagenow ) return;
global $current_user;
if ( get_option( $opt_name = "_se_debug_user_submitted_pass" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {
// the password has changed.
echo "Password has changed!";
/* do things here */
delete_option( $opt_name ); // do only once
}
});
```
That should work and as long as in `profile.php` page (updating own profile).
To capture the password, after this line:
`update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );`
update a custom option with the new password value `$pass2` which is the password confirmation, and call this option within `// the password has changed.` wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.
One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).
Hope that helps somehow.
|
232,269 |
<p>I've spent a day or so on this now and I'm turning to the community for assistance.</p>
<p>Firstly, I am trying to achieve something like this post:</p>
<p><a href="https://wordpress.stackexchange.com/questions/27158/wordpress-multiple-category-search">Wordpress Multiple Category Search</a></p>
<p>In my theme template, I have a custom search form:</p>
<pre><code><form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="Search..."></input>
<button type="submit">Search</button>
<div class="clear"></div>
<div class="search_category_section">
<?php
$args = array('parent' => 0);
$categories = get_categories($args);
echo '<div class="search_category_section">';
foreach ($categories as $category) {
$thecatid = $category->cat_ID;
echo '<div class="categorylist"><div class="parent_category_list_item"><input id="', $thecatid, '" type="checkbox" name="category_name" value="', $category->slug, '"><label for="', $thecatid, '">', $category->name, '</label></input></div>';
$childcats=get_categories(array('parent' => $thecatid));
foreach($childcats as $c) {
echo '<div class="child_category_list_item"><input id="', $c->cat_ID, '" type="checkbox" name="category_name" value="', $c->slug, '"><label for="', $c->cat_ID, '">', $c->name, '</label></input></div>';
}
echo '</div>';
}
?>
</div>
</fieldset>
</code></pre>
<p></p>
<p>So, let's say for example I search for "keyword", and I select two checkboxes, "category A" and "category B". I have two posts, one in each category. Each of those two posts has that keyword in it. After hitting the submit button it generates the following URL:</p>
<p>mydomain.com/?s=keyword&category_name=category-a&category_name=category-b</p>
<p>What this is currently doing is presenting me with one result - that is, one post from category B with that keyword in it.</p>
<p>What I'm actually looking for is this result:</p>
<p>mydomain.com/?s=keyword&category_name=category-a,category-b</p>
<p>Whereby I get all posts in all categories, with that keyword in it.</p>
<p>I've looked high and low, and while I've found results where others were trying to achieve a similar thing, none of their solutions worked for me.</p>
<p>This is all part of a learning curve for me. I have found <a href="https://wordpress.org/plugins/search-filter/" rel="nofollow noreferrer">this plugin</a> which looks like it will do what I want, but as you've all probably been in this situation whereby "I wish I could do this myself so that I understand better how the mechanics behind Wordpress" work I hope you'll appreciate the question.</p>
<p>Thanks in advance, if anything isn't clear or I've left vital info out let me know.</p>
|
[
{
"answer_id": 232270,
"author": "Preethi Sasankan",
"author_id": 92003,
"author_profile": "https://wordpress.stackexchange.com/users/92003",
"pm_score": 2,
"selected": false,
"text": "<p><strong>let’s start by defining an HTML search form:</strong></p>\n\n<pre><code><form method=\"get\" action=\"<?php bloginfo('url'); ?>\">\n<fieldset>\n<input type=\"text\" name=\"s\" value=\"\" placeholder=\"search&hellip;\" maxlength=\"50\" required=\"required\" />\n<p>Refine search to posts containing chosen tags:</p>\n<?php\n// generate list of categories\n$tags = get_categories();\nforeach ($tags as $tag) {\n echo \n '<label>',\n '<input type=\"checkbox\" name=\"taglist[]\" value=\"', $tag->slug, '\" /> ',\n $tag->name,\n \"</label>\\n\";\n}\n?>\n<button type=\"submit\">Search</button>\n</fieldset>\n</form>\n</code></pre>\n\n<p><strong>Add this to functions.php</strong></p>\n\n<pre><code>function advanced_search_query($query) {\n\n if($query->is_search()) {\n\n // tag search\n if (isset($_GET['taglist']) && is_array($_GET['taglist'])) {\n $query->set('tag_slug__and', $_GET['taglist']);\n }\n\n return $query;\n }\n\n}\nadd_action('pre_get_posts', 'advanced_search_query', 1000);\n</code></pre>\n"
},
{
"answer_id": 232351,
"author": "MisterH",
"author_id": 98327,
"author_profile": "https://wordpress.stackexchange.com/users/98327",
"pm_score": 2,
"selected": true,
"text": "<p>Here is what worked for me.</p>\n\n<p>Preethis answer almost got there, but no data was getting set. I needed to find a way of accessing the data in the array, and I used implode to do it.</p>\n\n<p>So here is my final code that enabled me to create a search form that loops and displays categories, allows the user to do a keyword search via any number of categories, and display results IF the keyword exists in any of the categories selected:</p>\n\n<p>I created a <strong>searchform.php</strong> file in my theme file and included the following HTML:</p>\n\n<pre><code><form id=\"searchform\" method=\"get\" action=\"<?php bloginfo('url'); ?>\">\n<fieldset>\n\n <input type=\"text\" name=\"s\" value=\"\" placeholder=\"Search...\"></input>\n <button type=\"submit\">Search</button>\n <div class=\"clear\"></div>\n <div class=\"search_category_section\">\n <?php\n $args = array('parent' => 0);\n $categories = get_categories($args);\n\n echo '<div class=\"search_category_section\">';\n\n foreach ($categories as $category) {\n\n $thecatid = $category->cat_ID;\n echo '<div class=\"categorylist\"><div class=\"parent_category_list_item\"><input id=\"', $thecatid, '\" type=\"checkbox\" name=\"category_name[]\" value=\"', $category->slug, '\"><label for=\"', $thecatid, '\">', $category->name, '</label></input></div>';\n $childcats=get_categories(array('parent' => $thecatid));\n foreach($childcats as $c) {\n echo '<div class=\"child_category_list_item\"><input id=\"', $c->cat_ID, '\" type=\"checkbox\" name=\"category_name[]\" value=\"', $c->slug, '\"><label for=\"', $c->cat_ID, '\">', $c->name, '</label></input></div>';\n }\n echo '</div>';\n }\n ?>\n </div>\n</fieldset>\n</code></pre>\n\n<p></p>\n\n<p>and then, my <strong>functions.php</strong> has the following code:</p>\n\n<pre><code><?php\n function advanced_search_query($query) {\n if($query->is_search()) {\n $get_the_category_name = $_GET['category_name'];\n if (isset($get_the_category_name) && is_array($get_the_category_name)) { \n $catnames = implode(\",\",$get_the_category_name);\n $query->set('category_name', $catnames);\n return $query;\n }\n }\n }\n add_action('pre_get_posts', 'advanced_search_query');\n ?>\n</code></pre>\n\n<p>if you do:</p>\n\n<pre><code>var_dump($get_the_category_name);\n</code></pre>\n\n<p>You'll get:</p>\n\n<pre><code>array(2) { [0]=> string(22) \"category-a\" [1]=> string(25) \"category-b\" } \n</code></pre>\n\n<p>Run implode() on that </p>\n\n<pre><code>string(48) \"human-element-analysis,latent-defects-check-list\" \n</code></pre>\n\n<p>Stick that string in a variable, set it in query as category_name, win.</p>\n\n<p>Thanks again Preethi for putting me in the right direction, and hope the above helps anyone looking to do the same!</p>\n"
}
] |
2016/07/14
|
[
"https://wordpress.stackexchange.com/questions/232269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98327/"
] |
I've spent a day or so on this now and I'm turning to the community for assistance.
Firstly, I am trying to achieve something like this post:
[Wordpress Multiple Category Search](https://wordpress.stackexchange.com/questions/27158/wordpress-multiple-category-search)
In my theme template, I have a custom search form:
```
<form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="Search..."></input>
<button type="submit">Search</button>
<div class="clear"></div>
<div class="search_category_section">
<?php
$args = array('parent' => 0);
$categories = get_categories($args);
echo '<div class="search_category_section">';
foreach ($categories as $category) {
$thecatid = $category->cat_ID;
echo '<div class="categorylist"><div class="parent_category_list_item"><input id="', $thecatid, '" type="checkbox" name="category_name" value="', $category->slug, '"><label for="', $thecatid, '">', $category->name, '</label></input></div>';
$childcats=get_categories(array('parent' => $thecatid));
foreach($childcats as $c) {
echo '<div class="child_category_list_item"><input id="', $c->cat_ID, '" type="checkbox" name="category_name" value="', $c->slug, '"><label for="', $c->cat_ID, '">', $c->name, '</label></input></div>';
}
echo '</div>';
}
?>
</div>
</fieldset>
```
So, let's say for example I search for "keyword", and I select two checkboxes, "category A" and "category B". I have two posts, one in each category. Each of those two posts has that keyword in it. After hitting the submit button it generates the following URL:
mydomain.com/?s=keyword&category\_name=category-a&category\_name=category-b
What this is currently doing is presenting me with one result - that is, one post from category B with that keyword in it.
What I'm actually looking for is this result:
mydomain.com/?s=keyword&category\_name=category-a,category-b
Whereby I get all posts in all categories, with that keyword in it.
I've looked high and low, and while I've found results where others were trying to achieve a similar thing, none of their solutions worked for me.
This is all part of a learning curve for me. I have found [this plugin](https://wordpress.org/plugins/search-filter/) which looks like it will do what I want, but as you've all probably been in this situation whereby "I wish I could do this myself so that I understand better how the mechanics behind Wordpress" work I hope you'll appreciate the question.
Thanks in advance, if anything isn't clear or I've left vital info out let me know.
|
Here is what worked for me.
Preethis answer almost got there, but no data was getting set. I needed to find a way of accessing the data in the array, and I used implode to do it.
So here is my final code that enabled me to create a search form that loops and displays categories, allows the user to do a keyword search via any number of categories, and display results IF the keyword exists in any of the categories selected:
I created a **searchform.php** file in my theme file and included the following HTML:
```
<form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="Search..."></input>
<button type="submit">Search</button>
<div class="clear"></div>
<div class="search_category_section">
<?php
$args = array('parent' => 0);
$categories = get_categories($args);
echo '<div class="search_category_section">';
foreach ($categories as $category) {
$thecatid = $category->cat_ID;
echo '<div class="categorylist"><div class="parent_category_list_item"><input id="', $thecatid, '" type="checkbox" name="category_name[]" value="', $category->slug, '"><label for="', $thecatid, '">', $category->name, '</label></input></div>';
$childcats=get_categories(array('parent' => $thecatid));
foreach($childcats as $c) {
echo '<div class="child_category_list_item"><input id="', $c->cat_ID, '" type="checkbox" name="category_name[]" value="', $c->slug, '"><label for="', $c->cat_ID, '">', $c->name, '</label></input></div>';
}
echo '</div>';
}
?>
</div>
</fieldset>
```
and then, my **functions.php** has the following code:
```
<?php
function advanced_search_query($query) {
if($query->is_search()) {
$get_the_category_name = $_GET['category_name'];
if (isset($get_the_category_name) && is_array($get_the_category_name)) {
$catnames = implode(",",$get_the_category_name);
$query->set('category_name', $catnames);
return $query;
}
}
}
add_action('pre_get_posts', 'advanced_search_query');
?>
```
if you do:
```
var_dump($get_the_category_name);
```
You'll get:
```
array(2) { [0]=> string(22) "category-a" [1]=> string(25) "category-b" }
```
Run implode() on that
```
string(48) "human-element-analysis,latent-defects-check-list"
```
Stick that string in a variable, set it in query as category\_name, win.
Thanks again Preethi for putting me in the right direction, and hope the above helps anyone looking to do the same!
|
232,278 |
<p>I have a plugin that reads data from an uploaded file and runs queries on the wp database. These inserts are into a table created by my plugin, so they aren't the post type.</p>
<p>This is how I got it working: </p>
<pre><code>$connection = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_query($connection, $query);
</code></pre>
<p>The problem with this is that I have to declare these variables (<strong><em>$db_host, $db_user, $db_pass, $db_name</em></strong>) inside the plugin source code. </p>
<p>Is there a way I can insert data into my custom tables with the wp api? Or is there a way I can pull these variables from an external file that I can ignore in a version control setup?</p>
|
[
{
"answer_id": 232284,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 3,
"selected": false,
"text": "<p>Why not study about how <strong>$wpdb</strong> works. Visit <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n\n<p>Here is a example of how to insert data to database using <strong>$wpdb</strong></p>\n\n<pre><code><?php\n global $wpdb;\n\n $wpdb->insert( \n 'table_name_here', \n array( \n 'column1' => 'value1', \n 'column2' => 123 \n ), \n array( \n '%s', \n '%d' \n ) \n );\n?>\n</code></pre>\n\n<p>Visit <a href=\"https://codex.wordpress.org/Creating_Tables_with_Plugins\" rel=\"noreferrer\">https://codex.wordpress.org/Creating_Tables_with_Plugins</a> for more .</p>\n"
},
{
"answer_id": 232297,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 4,
"selected": true,
"text": "<p>That's not a good practice trying to connect the DB by your own methods while WP does it for you initially.</p>\n\n<hr>\n\n<blockquote>\n <p>The problem with this is that I have to declare these variables\n ($db_host, $db_user, $db_pass, $db_name) inside the plugin source\n code.</p>\n</blockquote>\n\n<p>All these properties are defined in <code>wp-config.php</code> file, located in the root area.</p>\n\n<p>If you were to get these constants then, just include the file and call the constants, or use REGEX (better use REGEX, because there might be other callbacks that require loading WordPress)</p>\n\n<pre><code>// loading the config file to pull the DB_* constants\n$dirname = dirname(__FILE__);\n$root = false !== mb_strpos( $dirname, 'wp-content' ) ? mb_substr( $dirname, 0, mb_strpos( $dirname, 'wp-content' ) ) : $dirname;\n// if $root is not correct, provide a static path then, $root = '/path/to/root/dir'\n// assuming constants are ready (wp is configured), let's get them.\nrequire_once( $root . \"wp-config.php\" );\necho var_dump(\n 'DB name', DB_NAME,\n 'DB user', DB_USER,\n 'DB password', DB_PASSWORD,\n 'DB host', DB_HOST\n);\n</code></pre>\n\n<hr>\n\n<p>Here's a better solution:</p>\n\n<p><strong>Load WordPress</strong></p>\n\n<p><code>require( '/wp-blog-header.php' );</code> You should provide a working path to that file!</p>\n\n<p>To test if you have loaded WordPress successfully, dump out something:</p>\n\n<pre><code>add_action(\"wp\", function() { \n echo sprintf( \"Yes! I am creating with WordPress v. %s!\\n\", get_bloginfo(\"version\") );\n exit(\"I exits\\n\");\n});\n</code></pre>\n\n<p><strong>Now use WordPress DB API</strong></p>\n\n<p>To insert data, there's this <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row\" rel=\"noreferrer\"><code>wpdb::insert</code></a> you should use. Here the syntax</p>\n\n<p><code>$wpdb->insert( $table, $data, $format );</code> and example use:</p>\n\n<pre><code>$wpdb->insert( \n 'messages', \n array( \n 'PM_ID' => (int) $pm_id,\n 'sender' => $current_user->ID,\n 'recipient' => (int) $recipient,\n 'message' => \"Hello!\\n\",\n 'date' => time()\n )\n);\n$record_id = $wpdb->insert_id;\n</code></pre>\n\n<p>In the example, the array in <code>$wpdb->insert</code>'s 2nd param is an array with indexes as columns names, and values to be inserted for these cols in an independent record that you can get its ID with <code>$wpdb->insert_id</code> which gets last record insert ID in that table.</p>\n\n<p>Hope that helps, if at least you stay away from SQL injection using <code>$wpdb::insert</code> or prepared statements instead of direct queries.</p>\n"
},
{
"answer_id": 232586,
"author": "Navin Bhudiya",
"author_id": 98536,
"author_profile": "https://wordpress.stackexchange.com/users/98536",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php \nglobal $wpdb;\n $table=\"test_table\";\n$store_arr[\"name\"]=\"test\";\n$store_arr[\"email\"]=\"[email protected]\";\n\n$wpdb->insert( $table, $store_arr);\n ?> \n</code></pre>\n"
}
] |
2016/07/14
|
[
"https://wordpress.stackexchange.com/questions/232278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98214/"
] |
I have a plugin that reads data from an uploaded file and runs queries on the wp database. These inserts are into a table created by my plugin, so they aren't the post type.
This is how I got it working:
```
$connection = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_query($connection, $query);
```
The problem with this is that I have to declare these variables (***$db\_host, $db\_user, $db\_pass, $db\_name***) inside the plugin source code.
Is there a way I can insert data into my custom tables with the wp api? Or is there a way I can pull these variables from an external file that I can ignore in a version control setup?
|
That's not a good practice trying to connect the DB by your own methods while WP does it for you initially.
---
>
> The problem with this is that I have to declare these variables
> ($db\_host, $db\_user, $db\_pass, $db\_name) inside the plugin source
> code.
>
>
>
All these properties are defined in `wp-config.php` file, located in the root area.
If you were to get these constants then, just include the file and call the constants, or use REGEX (better use REGEX, because there might be other callbacks that require loading WordPress)
```
// loading the config file to pull the DB_* constants
$dirname = dirname(__FILE__);
$root = false !== mb_strpos( $dirname, 'wp-content' ) ? mb_substr( $dirname, 0, mb_strpos( $dirname, 'wp-content' ) ) : $dirname;
// if $root is not correct, provide a static path then, $root = '/path/to/root/dir'
// assuming constants are ready (wp is configured), let's get them.
require_once( $root . "wp-config.php" );
echo var_dump(
'DB name', DB_NAME,
'DB user', DB_USER,
'DB password', DB_PASSWORD,
'DB host', DB_HOST
);
```
---
Here's a better solution:
**Load WordPress**
`require( '/wp-blog-header.php' );` You should provide a working path to that file!
To test if you have loaded WordPress successfully, dump out something:
```
add_action("wp", function() {
echo sprintf( "Yes! I am creating with WordPress v. %s!\n", get_bloginfo("version") );
exit("I exits\n");
});
```
**Now use WordPress DB API**
To insert data, there's this [`wpdb::insert`](https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row) you should use. Here the syntax
`$wpdb->insert( $table, $data, $format );` and example use:
```
$wpdb->insert(
'messages',
array(
'PM_ID' => (int) $pm_id,
'sender' => $current_user->ID,
'recipient' => (int) $recipient,
'message' => "Hello!\n",
'date' => time()
)
);
$record_id = $wpdb->insert_id;
```
In the example, the array in `$wpdb->insert`'s 2nd param is an array with indexes as columns names, and values to be inserted for these cols in an independent record that you can get its ID with `$wpdb->insert_id` which gets last record insert ID in that table.
Hope that helps, if at least you stay away from SQL injection using `$wpdb::insert` or prepared statements instead of direct queries.
|
232,308 |
<p>I made a plugin that adds a shortcode with optional content. If there's no content, WordPress still tries looking for a closing tag. This is clearer with an example:</p>
<pre><code>[span class="foo"]
[span class="bar"]
[span class="baz"]stuff[/span]
</code></pre>
<p>Wanted:</p>
<pre><code><span class="foo"></span>
<span class="bar"></span>
<span class="baz">stuff</span>
</code></pre>
<p>Actual:</p>
<pre><code><span class="foo">
[span class="bar"]
[span class="baz"]stuff
</span>
</code></pre>
<p>Is there a way to make WordPress produce the first output? I'm expecting many of the plugin's users to be confused by this behavior. One way is to modify <code>the_content</code> before <code>do_shortcode</code> runs, but it's pretty hacky. Is there a clean or existing way to change this behavior?</p>
<p>Edit: I'm not asking why this behavior occurs, I'm asking for a good way to change this behavior.</p>
|
[
{
"answer_id": 232332,
"author": "webHasan",
"author_id": 44137,
"author_profile": "https://wordpress.stackexchange.com/users/44137",
"pm_score": 3,
"selected": false,
"text": "<p>Wordpress interpreted your shortcode like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4S0P0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4S0P0.png\" alt=\"Wordpress thought your shortcode like\"></a></p>\n\n<p>The main issue being, that you have a unclosed shortcode of the same tag in front of an enclosing shortcode of the same tag, which won't be parsed correctly. The documentation states that you might run into problems with <a href=\"https://codex.wordpress.org/Shortcode_API#Unclosed_Shortcodes\" rel=\"nofollow noreferrer\">unclosed shortcodes</a>.</p>\n\n<p>When you call your shortcode like this:</p>\n\n<pre><code>[span class=\"foo\" /]\n[span class=\"bar\" /]\n[span class=\"baz\"]stuff[/span]\n</code></pre>\n\n<p>You will get your expected result.</p>\n\n<p>Because the <a href=\"https://codex.wordpress.org/Shortcode_API#Self-Closing\" rel=\"nofollow noreferrer\">self-closing marker</a> <code>/</code> is needed in your use-case, although it generally is considered optional, but as it forces the parser to ignore following closing tags it gets you your expected result.</p>\n\n<p>The above solution is the correct usage of shortcodes according to the <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">WordPress Shortcode API</a>. If you want to to pre-process your shortcode in one way or another you can do that, but generally just make your users use the correct syntax in the first place. </p>\n"
},
{
"answer_id": 235198,
"author": "Jim Maguire",
"author_id": 63669,
"author_profile": "https://wordpress.stackexchange.com/users/63669",
"pm_score": 0,
"selected": false,
"text": "<p>A shortcode has nothing to do with opening and closing tags! A shortcode is a way to execute a function and output the results into content. </p>\n\n<p>add_shortcode('hello', myFunction);\nfunction myFunction (){return 'Hello world';}</p>\n\n<p>Putting the shortcode [hello] in your post will output Hello World.</p>\n"
}
] |
2016/07/15
|
[
"https://wordpress.stackexchange.com/questions/232308",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23538/"
] |
I made a plugin that adds a shortcode with optional content. If there's no content, WordPress still tries looking for a closing tag. This is clearer with an example:
```
[span class="foo"]
[span class="bar"]
[span class="baz"]stuff[/span]
```
Wanted:
```
<span class="foo"></span>
<span class="bar"></span>
<span class="baz">stuff</span>
```
Actual:
```
<span class="foo">
[span class="bar"]
[span class="baz"]stuff
</span>
```
Is there a way to make WordPress produce the first output? I'm expecting many of the plugin's users to be confused by this behavior. One way is to modify `the_content` before `do_shortcode` runs, but it's pretty hacky. Is there a clean or existing way to change this behavior?
Edit: I'm not asking why this behavior occurs, I'm asking for a good way to change this behavior.
|
Wordpress interpreted your shortcode like this:
[](https://i.stack.imgur.com/4S0P0.png)
The main issue being, that you have a unclosed shortcode of the same tag in front of an enclosing shortcode of the same tag, which won't be parsed correctly. The documentation states that you might run into problems with [unclosed shortcodes](https://codex.wordpress.org/Shortcode_API#Unclosed_Shortcodes).
When you call your shortcode like this:
```
[span class="foo" /]
[span class="bar" /]
[span class="baz"]stuff[/span]
```
You will get your expected result.
Because the [self-closing marker](https://codex.wordpress.org/Shortcode_API#Self-Closing) `/` is needed in your use-case, although it generally is considered optional, but as it forces the parser to ignore following closing tags it gets you your expected result.
The above solution is the correct usage of shortcodes according to the [WordPress Shortcode API](https://codex.wordpress.org/Shortcode_API). If you want to to pre-process your shortcode in one way or another you can do that, but generally just make your users use the correct syntax in the first place.
|
232,345 |
<p>I have PHP code</p>
<pre><code><?php if ($_SESSION['logged_in'] == 1) {
echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
echo '<script type="text/javascript">var logged_in=false;</script>';
}?>
</code></pre>
<p>It always returns <code>var logged_in=false;</code>. Where is mistake?</p>
|
[
{
"answer_id": 232346,
"author": "Александр",
"author_id": 88709,
"author_profile": "https://wordpress.stackexchange.com/users/88709",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\nif ( is_user_logged_in() ) {\n echo '<script type=\"text/javascript\">var logged_in=true;</script>';\n} else {\n echo '<script type=\"text/javascript\">var logged_in=false;</script>';\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 232432,
"author": "iszwnc",
"author_id": 90683,
"author_profile": "https://wordpress.stackexchange.com/users/90683",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow\"><code>is_user_logged_in()</code></a> function to check if the user is or not logged in the Dashboard.</p>\n\n<p>I do not know why you echo out a <code><script></code> tag, but if you want to integrate <em>PHP & JavaScript</em> altogether, I recommend you to take a look at <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">https://codex.wordpress.org/AJAX_in_Plugins</a>.</p>\n\n<p>This way you can pass data from the WordPress Back End to Front End and vice-versa through <strong>AJAX</strong> callbacks.</p>\n"
}
] |
2016/07/15
|
[
"https://wordpress.stackexchange.com/questions/232345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88709/"
] |
I have PHP code
```
<?php if ($_SESSION['logged_in'] == 1) {
echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
echo '<script type="text/javascript">var logged_in=false;</script>';
}?>
```
It always returns `var logged_in=false;`. Where is mistake?
|
```
<?php
if ( is_user_logged_in() ) {
echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
echo '<script type="text/javascript">var logged_in=false;</script>';
}
?>
```
|
232,409 |
<p>There is a major problem with most new templates for WordPress that want you to set your homepage to <strong><code>Your Latest Posts</code></strong>. </p>
<p>This is to enable many of the great theme features to work.</p>
<p>The problem with this is that the front page (even though not a blog page) is seen as a paged entity by the wordpress core and yoast seo too.</p>
<p>So what does this mean?</p>
<p>You have a homepage <code>www.mysite.com</code> if you visit your page and look inside the source code you see <strong><code>rel="next" href="hxxps://www.mysite.com/page/2/"</code></strong></p>
<p>If you actually click that /page/2 link you will see it takes you right back to your front page except this time if you look in the source code it now has <strong><code>rel="prev" href="hxxps://www.mysite.com/"</code></strong> and <strong><code>rel="next" href="hxxps://www.mysite.com/page/3/"</code></strong></p>
<p>If you click the link to <strong><code>/page/3/</code></strong> now and once again inspect the source code you will see <strong><code>rel="prev" href="hxxps://www.mysite.com/page/2/"</code></strong> and <strong><code>rel="next" href="hxxps://www.mysite.com/page/4/"</code></strong></p>
<p>This goes on and on and is not something an end user will ever see but is very bad for search engines especially Google who will possibly see this as duplicate content.</p>
<p>I have been in support talks with Yoast for several weeks on this issue and they are adamant it's a theme problem and blames theme developers not using wp_enqueue correctly. For the most part I believe it is but it also means that a great majority of the most popular wordpress themes out there have this very same problem.</p>
<p>The only current way around this is to go into reading settings in wordpress and set your front page to a <code>static page</code> and your posts page to <code>your posts page</code>. Easy but you lose all the nice functionality of a really great template you just spent a week customizing or even paid good money for.</p>
<p>So while that may be a solution, it's not really a solution and it seems most theme developers do not know how to get around this.</p>
<p>I have had this problem with my past theme Tempera, I switched to a few new themes from <code>GraphPaperPress</code> and then also tried out one of the most popular themes <code>Zerif</code> and they all have this problem. </p>
<p>I have tried all sorts of code snippets in functions.php and I can get the rel=next and rel=prev to not display on the front page but then it also does not work on every other page like the /blog/ page where do you want these meta links and also on all the category pages which also need the rel=next and rel=prev links in order to tell search engines to keep crawling deeper.</p>
<p>I can do this switch to a static front page and get a decent looking front page, similar to the themes dynamic front page but there is so much functionality lost and its rather depressing to have to settle for less, especially with all the wonderful ajaxy and parallaxy things that are available today.</p>
<p>So is there actually a simple function to remove it from the home page only but to have it appear on pages like /blog/ /category1/ /category2/</p>
<p>Here are some I have tried but I am just not getting the conditional statements right or I am doing something else wrong but its been too long diagnosing this now and I think I am losing my mind for sure.</p>
<pre><code>function wpseo_disable_rel_next_home( $link ) {
if ( is_home() ) {
return false;
}
}
add_filter( 'wpseo_next_rel_link', 'wpseo_disable_rel_next_home' );
</code></pre>
<p>and </p>
<pre><code>function genesis () {
if ( !is_home() || !function_exists( 'genesis' ) )
$this->adjacent_rel_links();
}
</code></pre>
<p>and</p>
<pre><code>if ( is_front_page() && is_home() )
{
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action(‘wp_head’, ‘cor_rel_next_prev_pagination’);
}
</code></pre>
<p>Hope someone can solve this riddle. Anyone wanting to test this out can download the Zerif theme and make sure Yoast is installed too. Use their dynamic front page system and then create a blog page for a separate blog listing page.</p>
|
[
{
"answer_id": 232410,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>I see you already tried with wpseo_next_rel_link can try with this one more time.</p>\n\n<pre><code>function wpseo_disable_rel_next_hom () {\n if ( is_home() || is_front_page() ) {\n return '';\n }\n}\nadd_filter('wpseo_next_rel_link', 'wpseo_disable_rel_next_hom');\n</code></pre>\n\n<p>And one more thing as per as I know that is not Yoast SEO plugin issue. You can try with WordPress Default theme and then you will see the different.</p>\n"
},
{
"answer_id": 246438,
"author": "NiteRaven",
"author_id": 107155,
"author_profile": "https://wordpress.stackexchange.com/users/107155",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the answer:</p>\n\n<pre><code>function bg_disable_front_page_wpseo_next_rel_link( $link ) {\n if ( is_front_page() ) {\n return false;\n }\n\n return $link;\n}\nadd_filter( 'wpseo_next_rel_link', 'bg_disable_front_page_wpseo_next_rel_link' );\n</code></pre>\n\n<p>You have to return the $link, if you return nothing it will disable it for every single page...</p>\n"
},
{
"answer_id": 366566,
"author": "ytkah",
"author_id": 188044,
"author_profile": "https://wordpress.stackexchange.com/users/188044",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter( 'wpseo_next_rel_link', '__return_false' );\n</code></pre>\n\n<p>add the code in theme function file</p>\n"
}
] |
2016/07/16
|
[
"https://wordpress.stackexchange.com/questions/232409",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98424/"
] |
There is a major problem with most new templates for WordPress that want you to set your homepage to **`Your Latest Posts`**.
This is to enable many of the great theme features to work.
The problem with this is that the front page (even though not a blog page) is seen as a paged entity by the wordpress core and yoast seo too.
So what does this mean?
You have a homepage `www.mysite.com` if you visit your page and look inside the source code you see **`rel="next" href="hxxps://www.mysite.com/page/2/"`**
If you actually click that /page/2 link you will see it takes you right back to your front page except this time if you look in the source code it now has **`rel="prev" href="hxxps://www.mysite.com/"`** and **`rel="next" href="hxxps://www.mysite.com/page/3/"`**
If you click the link to **`/page/3/`** now and once again inspect the source code you will see **`rel="prev" href="hxxps://www.mysite.com/page/2/"`** and **`rel="next" href="hxxps://www.mysite.com/page/4/"`**
This goes on and on and is not something an end user will ever see but is very bad for search engines especially Google who will possibly see this as duplicate content.
I have been in support talks with Yoast for several weeks on this issue and they are adamant it's a theme problem and blames theme developers not using wp\_enqueue correctly. For the most part I believe it is but it also means that a great majority of the most popular wordpress themes out there have this very same problem.
The only current way around this is to go into reading settings in wordpress and set your front page to a `static page` and your posts page to `your posts page`. Easy but you lose all the nice functionality of a really great template you just spent a week customizing or even paid good money for.
So while that may be a solution, it's not really a solution and it seems most theme developers do not know how to get around this.
I have had this problem with my past theme Tempera, I switched to a few new themes from `GraphPaperPress` and then also tried out one of the most popular themes `Zerif` and they all have this problem.
I have tried all sorts of code snippets in functions.php and I can get the rel=next and rel=prev to not display on the front page but then it also does not work on every other page like the /blog/ page where do you want these meta links and also on all the category pages which also need the rel=next and rel=prev links in order to tell search engines to keep crawling deeper.
I can do this switch to a static front page and get a decent looking front page, similar to the themes dynamic front page but there is so much functionality lost and its rather depressing to have to settle for less, especially with all the wonderful ajaxy and parallaxy things that are available today.
So is there actually a simple function to remove it from the home page only but to have it appear on pages like /blog/ /category1/ /category2/
Here are some I have tried but I am just not getting the conditional statements right or I am doing something else wrong but its been too long diagnosing this now and I think I am losing my mind for sure.
```
function wpseo_disable_rel_next_home( $link ) {
if ( is_home() ) {
return false;
}
}
add_filter( 'wpseo_next_rel_link', 'wpseo_disable_rel_next_home' );
```
and
```
function genesis () {
if ( !is_home() || !function_exists( 'genesis' ) )
$this->adjacent_rel_links();
}
```
and
```
if ( is_front_page() && is_home() )
{
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action(‘wp_head’, ‘cor_rel_next_prev_pagination’);
}
```
Hope someone can solve this riddle. Anyone wanting to test this out can download the Zerif theme and make sure Yoast is installed too. Use their dynamic front page system and then create a blog page for a separate blog listing page.
|
Here is the answer:
```
function bg_disable_front_page_wpseo_next_rel_link( $link ) {
if ( is_front_page() ) {
return false;
}
return $link;
}
add_filter( 'wpseo_next_rel_link', 'bg_disable_front_page_wpseo_next_rel_link' );
```
You have to return the $link, if you return nothing it will disable it for every single page...
|
232,435 |
<p>I need some customization of WORDPRESS comment area, so I've used this code in my child theme :</p>
<pre><code> <div id="comments" class="x-comments-area">
<?php if ( have_comments() ) : ?>
<?php
//The author of current post
$author_ID = get_the_author_meta("ID");
//The current post ID
$p_ID = get_the_ID();
?>
<h2 class="h-comments-title"><span><?php _e( 'Comments' , '__x__' ); ?> <small>
<?php
//Number of guest comments
echo ztjalali_persian_num(number_format_i18n(count(get_comments(array('post_id' => $p_ID,'author__not_in' => array($author_ID))))));
?></small></span></h2>
<ol class="x-comments-list">
<?php
wp_list_comments( array(
'callback' => 'x_icon_comment',
'style' => 'ol'
) );
?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : ?>
<nav id="comment-nav-below" class="navigation" role="navigation">
<h1 class="visually-hidden"><?php _e( 'Comment navigation', '__x__' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', '__x__' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', '__x__' ) ); ?></div>
</nav>
<?php endif; ?>
<?php if ( ! comments_open() && get_comments_number() ) : ?>
<p class="nocomments"><?php _e( 'Comments are closed.' , '__x__' ); ?></p>
<?php endif; ?>
<?php endif; ?>
<?php
//Loading of smilies
ob_start(); cs_print_smilies(); $cs_print_smilies = ob_get_clean();
//Comment form re-arrangement
comment_form( array(
'comment_notes_before' => '',
'comment_notes_after' => '',
'id_submit' => 'entry-comment-submit',
'label_submit' => __( 'Submit' , '__x__' ),
'title_reply' => __( '<span>Leave a Comment</span>' , '__x__' ),
'fields' => array(
'author' =>
'<p class="comment-form-author">' .
'<input id="author" name="author" type="text" value="' . get_comment_author() . '" placeholder="' . __( 'Name *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'email' =>
'<p class="comment-form-email">' .
'<input id="email" name="email" type="email" aria-required="true" aria-invalid="false" value="' .get_comment_author_email() . '" placeholder="' . __( 'Email *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'url' =>
'<p class="comment-form-url">' .
'<input id="url" name="url" type="text" value="' . get_comment_author_url() . '" placeholder="' . __( 'URL', '__x__' ) . '" size="30" />' .
'</p>'
),
'comment_field' => '<p class="comment-form-comment">' .
'</br>'.
$cs_print_smilies .
'<textarea id="comment" name="comment" cols="45" rows="4" placeholder="' . _x( 'Comment *', 'noun', '__x__' ) . '" aria-required="true"></textarea>' .
'</p>'
) );
?>
</div>
</code></pre>
<p>But with using above code I will have these PHP notices in my published posts, above the comments area:</p>
<blockquote>
<pre><code>Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 28
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 46
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 309
</code></pre>
</blockquote>
<p>While I know the problem is not inside of comment-template.php file.</p>
<p>How may I get rid of them?</p>
|
[
{
"answer_id": 232460,
"author": "JMau",
"author_id": 31376,
"author_profile": "https://wordpress.stackexchange.com/users/31376",
"pm_score": 1,
"selected": false,
"text": "<p>This notice comes because object <code>$comments</code> is null. So the <code>have_comments()</code> must wrap all the thing to be sure there are comments before using any property.</p>\n\n<p>in your case :</p>\n\n<pre><code><?php if ( have_comments() ) : \n /* the code */\nendif; ?>\n</code></pre>\n"
},
{
"answer_id": 232583,
"author": "Omid Toraby",
"author_id": 62437,
"author_profile": "https://wordpress.stackexchange.com/users/62437",
"pm_score": 0,
"selected": false,
"text": "<p>It was about calling the fields value containers which are arrays, so:</p>\n\n<pre><code> get_comment_author()\n</code></pre>\n\n<p>should change to something like this:</p>\n\n<pre><code> $commenter['comment_author']\n</code></pre>\n"
},
{
"answer_id": 254057,
"author": "clap",
"author_id": 65450,
"author_profile": "https://wordpress.stackexchange.com/users/65450",
"pm_score": -1,
"selected": false,
"text": "<p>I have same problem when i had tried to change the default location of comment form input fields this error appears so first verify it and check the condition on comment template. Also try <code>define('WP_DEBUG', false);</code></p>\n"
}
] |
2016/07/17
|
[
"https://wordpress.stackexchange.com/questions/232435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62437/"
] |
I need some customization of WORDPRESS comment area, so I've used this code in my child theme :
```
<div id="comments" class="x-comments-area">
<?php if ( have_comments() ) : ?>
<?php
//The author of current post
$author_ID = get_the_author_meta("ID");
//The current post ID
$p_ID = get_the_ID();
?>
<h2 class="h-comments-title"><span><?php _e( 'Comments' , '__x__' ); ?> <small>
<?php
//Number of guest comments
echo ztjalali_persian_num(number_format_i18n(count(get_comments(array('post_id' => $p_ID,'author__not_in' => array($author_ID))))));
?></small></span></h2>
<ol class="x-comments-list">
<?php
wp_list_comments( array(
'callback' => 'x_icon_comment',
'style' => 'ol'
) );
?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : ?>
<nav id="comment-nav-below" class="navigation" role="navigation">
<h1 class="visually-hidden"><?php _e( 'Comment navigation', '__x__' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', '__x__' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', '__x__' ) ); ?></div>
</nav>
<?php endif; ?>
<?php if ( ! comments_open() && get_comments_number() ) : ?>
<p class="nocomments"><?php _e( 'Comments are closed.' , '__x__' ); ?></p>
<?php endif; ?>
<?php endif; ?>
<?php
//Loading of smilies
ob_start(); cs_print_smilies(); $cs_print_smilies = ob_get_clean();
//Comment form re-arrangement
comment_form( array(
'comment_notes_before' => '',
'comment_notes_after' => '',
'id_submit' => 'entry-comment-submit',
'label_submit' => __( 'Submit' , '__x__' ),
'title_reply' => __( '<span>Leave a Comment</span>' , '__x__' ),
'fields' => array(
'author' =>
'<p class="comment-form-author">' .
'<input id="author" name="author" type="text" value="' . get_comment_author() . '" placeholder="' . __( 'Name *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'email' =>
'<p class="comment-form-email">' .
'<input id="email" name="email" type="email" aria-required="true" aria-invalid="false" value="' .get_comment_author_email() . '" placeholder="' . __( 'Email *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'url' =>
'<p class="comment-form-url">' .
'<input id="url" name="url" type="text" value="' . get_comment_author_url() . '" placeholder="' . __( 'URL', '__x__' ) . '" size="30" />' .
'</p>'
),
'comment_field' => '<p class="comment-form-comment">' .
'</br>'.
$cs_print_smilies .
'<textarea id="comment" name="comment" cols="45" rows="4" placeholder="' . _x( 'Comment *', 'noun', '__x__' ) . '" aria-required="true"></textarea>' .
'</p>'
) );
?>
</div>
```
But with using above code I will have these PHP notices in my published posts, above the comments area:
>
>
> ```
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 28
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 46
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 309
>
> ```
>
>
While I know the problem is not inside of comment-template.php file.
How may I get rid of them?
|
This notice comes because object `$comments` is null. So the `have_comments()` must wrap all the thing to be sure there are comments before using any property.
in your case :
```
<?php if ( have_comments() ) :
/* the code */
endif; ?>
```
|
232,436 |
<p>So recently I moved a client from Blogger to Wordpress.</p>
<p>When the posts imported from blogger, it saved the blogger "labels" as "tags" in Wordpress. Since I'd like to have these as categories instead, I used a plugin to convert all tags to categories.</p>
<p>This worked fine and dandy, but it left Uncategorized on all of my posts. So now I have around 900 posts that all have their correct categories attached, as well as "Uncategorized".</p>
<p>So my goal is to remove "Uncategorized" from all 900 posts, but I'm struggling to find a speedy method to do this.</p>
<p>Does anyone know how I could accomplish this in a bulk method? </p>
|
[
{
"answer_id": 232441,
"author": "Simon Cossar",
"author_id": 59349,
"author_profile": "https://wordpress.stackexchange.com/users/59349",
"pm_score": 3,
"selected": false,
"text": "<p>With <a href=\"https://wp-cli.org/\">wp-cli</a> installed you can run a bash script like this to remove the 'uncategorized' category from all posts with more than one category</p>\n\n<pre><code>#!/bin/bash\n\nfor post in $(wp post list --field=ID)\ndo\n count=$(wp post term list $post 'category' --fields='name' --format=\"count\")\n if [ \"$count\" -gt \"1\" ]\n then\n wp post term remove $post category 'uncategorized'\n fi\ndone\n</code></pre>\n\n<p>Save this as something like <code>delete_uncategorized.bash</code> and then run <code>bash delete_uncategorized.bash</code> from the command line.</p>\n"
},
{
"answer_id": 253240,
"author": "TechSmurfy",
"author_id": 111344,
"author_profile": "https://wordpress.stackexchange.com/users/111344",
"pm_score": 2,
"selected": false,
"text": "<p>A bit late to the party guys, but I just needed to do this myself. A workaround would be via SQL queries in phpmyadmin, something like:</p>\n\n<pre><code>SELECT *\nFROM `wp_term_relationships`\nWHERE `term_taxonomy_id`\nIN ( SELECT `term_taxonomy_id`\nFROM `wp_term_taxonomy`\nWHERE `taxonomy` = 'category' )\nGROUP BY `object_id`\nHAVING ( COUNT( `object_id` ) >1 )\n</code></pre>\n\n<p>(replace wp_ prefix with your prefix)\nUsually \"uncategorized\" has a <em>term_taxonomy_id</em> = 1. The above query would group all the post ids where there is more than one category, so naturally \"uncategorized\" is displayed first in the grouping. So select all those rows that have a <em>term_taxonomy_id</em> = 1 and delete them. And that's about it!</p>\n\n<p>Now all you have to do is edit the <em>count</em> field of \"uncategorized\" (<em>term_taxonomy_id</em> = 1) in the <em>wp_term_taxonomy</em> table. Count number is how many articles are listed in this category, but the specific field is not updated automatically. </p>\n\n<p>If you go to your wp admin panel, categories section, the old (wrong) count number is still displayed, but if you press that number and go to the posts list of 'uncategorized', wordpress usually recounts the posts that are affiliated with that category. A correct count will be displayed on your top right, so go then into your db, and edit the <em>count</em> field accordingly :)</p>\n\n<p>Edit: Actually, the count does get eventually updated, just not right away, so you may want to skip the manual count update.</p>\n"
},
{
"answer_id": 256884,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a plugin that upon activation, loops through all the posts that are in the uncategorized category. If it's in another category, it removes uncategorized. Further, when a post is saved, it does the same check.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Remove Uncategorized\n * Description: Removes the uncategorized category if there's another category.\n * Author: Nathan Johnson\n * Licence: GPL2+\n * Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html\n */\n\n//* Don't access this file directly\ndefined( 'ABSPATH' ) or die();\n\nregister_activation_hook( __FILE__ , 'wpse_106269_activation' );\n\nfunction wpse_106269_activation() {\n $args = array(\n 'posts_per_page' => -1,\n 'offset' => 0,\n 'category' => get_option( 'default_category' ),\n 'post_status' => 'any',\n 'suppress_filters' => true,\n );\n $posts = get_posts( $args );\n foreach( $posts as $post ) {\n wpse_106269_maybe_remove_uncategorized_category( $post->ID );\n }\n}\n\nadd_action( 'save_post', 'wpse_106269_save_post', 10, 3 );\n\nfunction wpse_106269_save_post( $id, $post, $update ) {\n remove_action( 'save_post', 'wpse_106269_save_post', 10, 3 );\n wpse_106269_maybe_remove_uncategorized_category( $id );\n add_action( 'save_post', 'wpse_106269_save_post', 10, 3 );\n}\n\nfunction wpse_106269_maybe_remove_uncategorized_category( $id ) {\n $categories = get_the_category( $id );\n $default = get_cat_name( get_option( 'default_category' ) );\n if( count( $categories ) >= 2 && in_category( $default, $id ) ) {\n wp_remove_object_terms( $id, $default, 'category' );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 272958,
"author": "Jamie Chong",
"author_id": 123575,
"author_profile": "https://wordpress.stackexchange.com/users/123575",
"pm_score": 0,
"selected": false,
"text": "<p>Based on @TechSmurfy's answer I came up with this: </p>\n\n<pre><code>create temporary table tr_to_delete (object_id INT);\ninsert into tr_to_delete SELECT object_id FROM wp_term_relationships tr, wp_term_taxonomy tt WHERE tr.term_taxonomy_id=tt.term_taxonomy_id and tt.taxonomy='category' GROUP BY object_id HAVING COUNT(*) >1;\ndelete from wp_term_relationships where term_taxonomy_id=1 and object_id in (select object_id from tr_to_delete);\ndrop temporary table tr_to_delete;\n</code></pre>\n"
},
{
"answer_id": 272964,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Well, the easiest way without messing with the database is to create a new category, make that the default, then go into the posts list and sort by the 'uncategorized' category. Edit those posts and remove the 'uncategorized' category tag.</p>\n\n<p>Once that is completed, you can delete the category. A category cannot be deleted if any post uses that category.</p>\n"
},
{
"answer_id": 290337,
"author": "dulesaga",
"author_id": 134380,
"author_profile": "https://wordpress.stackexchange.com/users/134380",
"pm_score": 0,
"selected": false,
"text": "<p>After messing around and trying all the approaches from above, I found that this sql query is the fastest way to remove posts from Uncategorized that have more than one cat.</p>\n\n<p>Using WP-CLI would be the best option, if it wasn't slow as hell. </p>\n\n<p>In my case I had to delete more than 50 000 term relationships, so it just FAILED.</p>\n\n<pre><code>DELETE FROM wp_term_relationships WHERE term_taxonomy_id=1 AND object_id IN ( SELECT object_id FROM (\nSELECT tr.object_id FROM wp_term_relationships tr, wp_term_taxonomy tt WHERE tr.term_taxonomy_id=tt.term_taxonomy_id and tt.taxonomy='category' GROUP BY tr.object_id HAVING COUNT(*) >1\n) as temp_table);\n</code></pre>\n"
}
] |
2016/07/17
|
[
"https://wordpress.stackexchange.com/questions/232436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75134/"
] |
So recently I moved a client from Blogger to Wordpress.
When the posts imported from blogger, it saved the blogger "labels" as "tags" in Wordpress. Since I'd like to have these as categories instead, I used a plugin to convert all tags to categories.
This worked fine and dandy, but it left Uncategorized on all of my posts. So now I have around 900 posts that all have their correct categories attached, as well as "Uncategorized".
So my goal is to remove "Uncategorized" from all 900 posts, but I'm struggling to find a speedy method to do this.
Does anyone know how I could accomplish this in a bulk method?
|
With [wp-cli](https://wp-cli.org/) installed you can run a bash script like this to remove the 'uncategorized' category from all posts with more than one category
```
#!/bin/bash
for post in $(wp post list --field=ID)
do
count=$(wp post term list $post 'category' --fields='name' --format="count")
if [ "$count" -gt "1" ]
then
wp post term remove $post category 'uncategorized'
fi
done
```
Save this as something like `delete_uncategorized.bash` and then run `bash delete_uncategorized.bash` from the command line.
|
232,462 |
<p>I'm trying to return only pages in search results.</p>
<p>This is working:</p>
<p><code>/?s=term&post_type=post</code></p>
<p>It returns only posts, no pages.</p>
<p>But the opposite is not working:</p>
<p><code>/?s=term&post_type=page</code></p>
<p>This is returning pages and posts.</p>
<p>How do I return only pages?</p>
<p><strong>Edit</strong></p>
<p>Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.</p>
<pre><code><a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
</code></pre>
<p>So, I can't just globally set all search results to only be one or the other.</p>
|
[
{
"answer_id": 232467,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>You can enforce a post type per callback on <code>pre_get_posts</code>:</p>\n\n<pre><code>is_admin() || add_action( 'pre_get_posts', function( \\WP_Query $query ) {\n\n $post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );\n\n if ( $post_type && $query->is_main_query() && $query->is_search() )\n $query->set( 'post_type', [ $post_type ] );\n});\n</code></pre>\n\n<p>If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin.</p>\n"
},
{
"answer_id": 359882,
"author": "Rajeev",
"author_id": 177282,
"author_profile": "https://wordpress.stackexchange.com/users/177282",
"pm_score": -1,
"selected": false,
"text": "<p>In your search.php, find The Loop and insert this code just after it. You can recognize the Loop because it usually starts with:</p>\n\n<pre><code><?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>\n</code></pre>\n\n<p><strong><em>Code to be inserted:</em></strong></p>\n\n<pre><code>if (is_search() && ($post->post_type=='post')) continue; \n</code></pre>\n\n<p>So, your code should be like this:</p>\n\n<pre><code><?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>\n<?php if (is_search() && ($post->post_type=='post')) continue; ?>\n</code></pre>\n\n<p>Let me know if it worked.</p>\n"
}
] |
2016/07/17
|
[
"https://wordpress.stackexchange.com/questions/232462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75134/"
] |
I'm trying to return only pages in search results.
This is working:
`/?s=term&post_type=post`
It returns only posts, no pages.
But the opposite is not working:
`/?s=term&post_type=page`
This is returning pages and posts.
How do I return only pages?
**Edit**
Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.
```
<a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
```
So, I can't just globally set all search results to only be one or the other.
|
You can enforce a post type per callback on `pre_get_posts`:
```
is_admin() || add_action( 'pre_get_posts', function( \WP_Query $query ) {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
if ( $post_type && $query->is_main_query() && $query->is_search() )
$query->set( 'post_type', [ $post_type ] );
});
```
If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin.
|
232,465 |
<p>I am trying to write a function to upload and delete images on frontend with dropzonejs uploader, and so far i managed to make everything work.</p>
<p>But the problem is that i need to secure it that the image that is deleting is actually uploaded by the user who is deleting image.</p>
<p>In wordpress admin area in media library when i click on image, in attachments details there is a <code>Uploaded by</code> with username who uploaded specific image.</p>
<p>But on searching all over the net and wordpress codex i didn't find any info how to retrieve user id who uploaded the image.</p>
<p>So id i have image id and try to delete with <code>wp_delete_attachment</code> is there a way to check who is the uploader of that image and compare logged in user id with image uploader id and if those two match delete the image.</p>
|
[
{
"answer_id": 232467,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>You can enforce a post type per callback on <code>pre_get_posts</code>:</p>\n\n<pre><code>is_admin() || add_action( 'pre_get_posts', function( \\WP_Query $query ) {\n\n $post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );\n\n if ( $post_type && $query->is_main_query() && $query->is_search() )\n $query->set( 'post_type', [ $post_type ] );\n});\n</code></pre>\n\n<p>If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin.</p>\n"
},
{
"answer_id": 359882,
"author": "Rajeev",
"author_id": 177282,
"author_profile": "https://wordpress.stackexchange.com/users/177282",
"pm_score": -1,
"selected": false,
"text": "<p>In your search.php, find The Loop and insert this code just after it. You can recognize the Loop because it usually starts with:</p>\n\n<pre><code><?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>\n</code></pre>\n\n<p><strong><em>Code to be inserted:</em></strong></p>\n\n<pre><code>if (is_search() && ($post->post_type=='post')) continue; \n</code></pre>\n\n<p>So, your code should be like this:</p>\n\n<pre><code><?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>\n<?php if (is_search() && ($post->post_type=='post')) continue; ?>\n</code></pre>\n\n<p>Let me know if it worked.</p>\n"
}
] |
2016/07/17
|
[
"https://wordpress.stackexchange.com/questions/232465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21135/"
] |
I am trying to write a function to upload and delete images on frontend with dropzonejs uploader, and so far i managed to make everything work.
But the problem is that i need to secure it that the image that is deleting is actually uploaded by the user who is deleting image.
In wordpress admin area in media library when i click on image, in attachments details there is a `Uploaded by` with username who uploaded specific image.
But on searching all over the net and wordpress codex i didn't find any info how to retrieve user id who uploaded the image.
So id i have image id and try to delete with `wp_delete_attachment` is there a way to check who is the uploader of that image and compare logged in user id with image uploader id and if those two match delete the image.
|
You can enforce a post type per callback on `pre_get_posts`:
```
is_admin() || add_action( 'pre_get_posts', function( \WP_Query $query ) {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
if ( $post_type && $query->is_main_query() && $query->is_search() )
$query->set( 'post_type', [ $post_type ] );
});
```
If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin.
|
232,471 |
<p>In content I can have multiple shortcodes like <code>[book id="1"] [book id="14" page="243"]</code></p>
<p>Is there any help method with which I can search the content for that shortcode and get its parameters? I need to get IDs so I can call WP_Query and append the Custom Post Types titles at the end.</p>
<pre><code>function filter_books( $content ) {
// get all shortcodes IDs and other parameters if they exists
...
return $content;
}
add_filter( 'the_content', 'filter_books', 15 );
</code></pre>
<p>I tried using following code but var_dump($matches) is empty and if it would work I am not sure how would I get parameters (<a href="https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list">https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list</a>)</p>
<pre><code> $shortcode = 'book';
preg_match('/\['.$shortcode.'\]/s', $content, $matches);
</code></pre>
|
[
{
"answer_id": 232648,
"author": "Marko",
"author_id": 47357,
"author_profile": "https://wordpress.stackexchange.com/users/47357",
"pm_score": 3,
"selected": true,
"text": "<p>This is working for me</p>\n\n<pre><code> $shortcode = 'book';\n $pattern = get_shortcode_regex();\n\n // if shortcode 'book' exists\n if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )\n && array_key_exists( 2, $matches )\n && in_array( $shortcode, $matches[2] ) ) {\n $shortcode_atts = array_keys($matches[2], $shortcode);\n\n // if shortcode has attributes\n if (!empty($shortcode_atts)) {\n foreach($shortcode_atts as $att) {\n preg_match('/id=\"(\\d+)\"/', $matches[3][$att], $book_id);\n\n // fill the id into main array\n $book_ids[] = $book_id[1];\n }\n}\n...\n</code></pre>\n"
},
{
"answer_id": 284157,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 1,
"selected": false,
"text": "<p>there is actually a much simpler way to achieve this. When the content is parsed by WP, it executes the shortcodes it finds in the content. As of WP 4.7 a new filter, <a href=\"https://developer.wordpress.org/reference/hooks/do_shortcode_tag/\" rel=\"nofollow noreferrer\">do_shortcode_tag</a> is triggered when a shortcode is replaced by its content. This is really useful to add additional content to the shortcode output based on the attributes found,</p>\n\n<pre><code>add_filter( 'do_shortcode_tag','add_my_script',10,3);\nfunction enqueue_my_script($output, $tag, $attr){\n if('aShortcode' != $tag){ //make sure it is the right shortcode\n return $output;\n }\n if(!isset($attr['id'])){ //you can even check for specific attributes\n return $output;\n }\n $output.='<script> ... </script>';\n return $output;\n}\n</code></pre>\n\n<p>alternatively, if you need to put something into the footer of your page, you could hook onto the <a href=\"https://developer.wordpress.org/reference/functions/wp_footer/\" rel=\"nofollow noreferrer\">wp_footer</a> action within the above function either an an <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#more-information\" rel=\"nofollow noreferrer\">anonymous function</a> or to fire another function in your file.</p>\n"
}
] |
2016/07/17
|
[
"https://wordpress.stackexchange.com/questions/232471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47357/"
] |
In content I can have multiple shortcodes like `[book id="1"] [book id="14" page="243"]`
Is there any help method with which I can search the content for that shortcode and get its parameters? I need to get IDs so I can call WP\_Query and append the Custom Post Types titles at the end.
```
function filter_books( $content ) {
// get all shortcodes IDs and other parameters if they exists
...
return $content;
}
add_filter( 'the_content', 'filter_books', 15 );
```
I tried using following code but var\_dump($matches) is empty and if it would work I am not sure how would I get parameters (<https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list>)
```
$shortcode = 'book';
preg_match('/\['.$shortcode.'\]/s', $content, $matches);
```
|
This is working for me
```
$shortcode = 'book';
$pattern = get_shortcode_regex();
// if shortcode 'book' exists
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( $shortcode, $matches[2] ) ) {
$shortcode_atts = array_keys($matches[2], $shortcode);
// if shortcode has attributes
if (!empty($shortcode_atts)) {
foreach($shortcode_atts as $att) {
preg_match('/id="(\d+)"/', $matches[3][$att], $book_id);
// fill the id into main array
$book_ids[] = $book_id[1];
}
}
...
```
|
232,490 |
<p>When I click on "older entries" in my home page, it goes to a second link but it shows the same posts. I think I need to modify something in the <code>index.php</code>, this is the full code section that I think I need to modify:</p>
<pre><code><div class="container">
<div class="post_content">
<div class="home_posts">
<?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 2),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>';
$type = get_post_meta($post->ID,'page_featured_type',true);
switch ($type) {
case 'youtube':
echo '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
break;
case 'vimeo':
echo '<iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&amp;byline=0&amp;portrait=0&amp;color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
break;
default:
echo '<div class="grid_post_img">
<a href="'.get_permalink().'">'.get_the_post_thumbnail().'</a>
</div>';
break;
}
echo '<div class="grid_home_posts">
<p>'.dess_get_excerpt(120).'</p>
</div>
</div>
';
endwhile;
?>
</div>
<?php
echo '<div class="load_more_content"><div class="load_more_text">';
ob_start();
next_posts_link('LOAD MORE',$query->max_num_pages);
$buffer = ob_get_contents();
ob_end_clean();
if(!empty($buffer)) echo $buffer;
echo'</div></div>';
$max_pages = $query->max_num_pages;
wp_reset_postdata();
endif;
?>
<span id="max-pages" style="display:none"><?php echo $max_pages ?></span>
</div>
<?php get_sidebar(); ?>
<div class="clear"></div>
</div>
</div>
</code></pre>
<p>Could it be here: </p>
<pre><code><?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
</code></pre>
<p>This is the URL to "Older entries": <a href="http://www.wha2wear.com/page/2/" rel="nofollow">http://www.wha2wear.com/page/2/</a> that shows the same content as the homepage. Also, I don't really see that "Older entries" is written somewhere in the code..</p>
<p>Also, in the actual page, Front Page page, there is this code</p>
<pre><code>[posts-for-page order_by ='date' hide_images='false' num='11' read_more='
Read More »' show_full_posts='false' use_wp_excerpt='true' strip_html='true' hide_post_content='false' show_meta='false' force_image_height='200' force_image_width='250']
</code></pre>
<p><strong>I have the feeling that this code has higher priority than the php, so the homepage does what it says there?</strong></p>
|
[
{
"answer_id": 232922,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>If the posts are being displayed via a static front page (they seem to be?) then you need to use the query parameter <code>page</code> not <code>paged</code>. You could try this:</p>\n\n<pre><code>$args2 = array(\n 'post_type' => 'post',\n 'posts_per_page' => 6,\n 'paged' => ( get_query_var('page') ? get_query_var('page') : 1),\n);\n</code></pre>\n\n<p>As mentioned on: <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_query_var</a></p>\n\n<p>Edit: note however the <code>paged</code> parameter is still set in the query array but the <code>page</code> query_var is used. This from example at: <a href=\"https://codex.wordpress.org/Function_Reference/WP_Query\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/WP_Query</a></p>\n"
},
{
"answer_id": 232923,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you try with default query and use like this </p>\n\n<pre><code>if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }\nelseif ( get_query_var('page') ) { $paged = get_query_var('page'); }\nelse { $paged = 1; }\n\n$args = array(\n'post_type' => 'post',\n'posts_per_page' => 6,\n'paged' => $paged,\n);\n\nquery_posts($args); while (have_posts()): the_post();\n\n// do something\n\nendwhile;\n</code></pre>\n\n<p>See here more details about Adding the \"paged\" parameter to a query</p>\n\n<p><a href=\"https://codex.wordpress.org/Pagination#Adding_the_.22paged.22_parameter_to_a_query\" rel=\"nofollow\">https://codex.wordpress.org/Pagination#Adding_the_.22paged.22_parameter_to_a_query</a></p>\n"
},
{
"answer_id": 233456,
"author": "ma_dev_15",
"author_id": 99113,
"author_profile": "https://wordpress.stackexchange.com/users/99113",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args=array(\n 'orderby'=> 'id',\n 'order' => 'desc',\n 'paged'=>$paged\n );\nglobal $wp_query;\n$original_query = $wp_query;\n$wp_query = null;\n$wp_query = new WP_Query( $args );\n if ( have_posts() ) : \n\n while ( have_posts() ):\n the_post(); \n\n\n get_template_part( 'template-parts/content', get_post_format());\n endif;\n\n $count++;\n endwhile;\n // If no content, include the \"No posts found\" template.\n else :\n get_template_part( 'template-parts/content', 'none' );\n\n endif;\n\n $nav = get_the_posts_pagination( array(\n 'mid_size' => 4,\n 'prev_text' => __( '&laquo;', 'twentysixteen' ),\n 'next_text' => __( '&raquo;', 'twentysixteen' ),\n 'before_page_number' => '<span class=\"meta-nav screen-reader-text\">' . __( '', 'twentysixteen' ) . ' </span>',\n 'screen_reader_text' => __( 'Post Navigation' )\n ) );\n\n $nav = str_replace('<h2 class=\"screen-reader-text\">Post Navigation</h2>', '', $nav);\n echo $nav;\n\n $wp_query = null;\n $wp_query = $original_query;\n wp_reset_postdata();$wp_query = null;\n $wp_query = $original_query;\n wp_reset_postdata();\n</code></pre>\n\n<p>this is how it will work, you need to update WP_Query, not to use another object, it wouldn't work with pagination.</p>\n"
}
] |
2016/07/18
|
[
"https://wordpress.stackexchange.com/questions/232490",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91761/"
] |
When I click on "older entries" in my home page, it goes to a second link but it shows the same posts. I think I need to modify something in the `index.php`, this is the full code section that I think I need to modify:
```
<div class="container">
<div class="post_content">
<div class="home_posts">
<?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 2),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>';
$type = get_post_meta($post->ID,'page_featured_type',true);
switch ($type) {
case 'youtube':
echo '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
break;
case 'vimeo':
echo '<iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&byline=0&portrait=0&color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
break;
default:
echo '<div class="grid_post_img">
<a href="'.get_permalink().'">'.get_the_post_thumbnail().'</a>
</div>';
break;
}
echo '<div class="grid_home_posts">
<p>'.dess_get_excerpt(120).'</p>
</div>
</div>
';
endwhile;
?>
</div>
<?php
echo '<div class="load_more_content"><div class="load_more_text">';
ob_start();
next_posts_link('LOAD MORE',$query->max_num_pages);
$buffer = ob_get_contents();
ob_end_clean();
if(!empty($buffer)) echo $buffer;
echo'</div></div>';
$max_pages = $query->max_num_pages;
wp_reset_postdata();
endif;
?>
<span id="max-pages" style="display:none"><?php echo $max_pages ?></span>
</div>
<?php get_sidebar(); ?>
<div class="clear"></div>
</div>
</div>
```
Could it be here:
```
<?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
```
This is the URL to "Older entries": <http://www.wha2wear.com/page/2/> that shows the same content as the homepage. Also, I don't really see that "Older entries" is written somewhere in the code..
Also, in the actual page, Front Page page, there is this code
```
[posts-for-page order_by ='date' hide_images='false' num='11' read_more='
Read More »' show_full_posts='false' use_wp_excerpt='true' strip_html='true' hide_post_content='false' show_meta='false' force_image_height='200' force_image_width='250']
```
**I have the feeling that this code has higher priority than the php, so the homepage does what it says there?**
|
Why don't you try with default query and use like this
```
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
$args = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
);
query_posts($args); while (have_posts()): the_post();
// do something
endwhile;
```
See here more details about Adding the "paged" parameter to a query
<https://codex.wordpress.org/Pagination#Adding_the_.22paged.22_parameter_to_a_query>
|
232,498 |
<p>I am currently working on <a href="http://www.highereg.com/member-list/starr-mazer" rel="nofollow noreferrer">this website</a> which uses a Wordpress theme designed by one Themeforest author. As can be seen via the link and the following screenshot from the same page, the theme's Portfolio (Custom Post Type) utilises 8 columns for textual and any other data -- with 4 other other columns to its right used in rendering a meta-box.</p>
<p><a href="https://i.stack.imgur.com/vJORp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vJORp.png" alt="The space bordered in Orange is empty and unused."></a></p>
<p>My issue is largely with the blank space under the meta-box. The page's design is such that while only a portion of those 4 columns are used for the box, the rest of that space beneath it goes unused.</p>
<p>I am looking to amend this design; I'd like to fit in other plugins (a Newsletter sign up box, for instance) below the meta-box in the space bordered in Orange and am unsure on what would be the best way to go about it.</p>
<p>The theme author is also unresponsive which rules out asking them about the same. The code used in the design of the pictured portion of the page is as follows -- </p>
<pre><code><div class="large-12 medium-12 columns">
<h2 class="portfolio-detail-title"><?php the_title(); ?></h2>
</div>
<div class="portfolio-detail-left large-8 medium-8 columns">
<div class="portfolio-detail-text">
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
</div>
</div>
<div class="portfolio-detail-right large-4 medium-4 columns ">
<div class="portfolio-detail-inner">
<div class="portfolio-detail">
<div class="portfolio-detail-content"><i class="fa fa-tag"></i> <span><?php the_terms( get_the_ID(), 'portfolio_categories' ); ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-user"></i> <span><?php echo esc_attr( $portfolio_client ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-home"></i> <span><?php echo esc_attr( $portfolio_location ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-bookmark-o"></i> <span><?php echo esc_attr( $portfolio_skills ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-cogs gears"></i> <span><?php echo esc_attr( $portfolio_rates ) ?></span></div>
<div class="portfolio-detail-url"><i class="fa fa-chain"></i> <a href="<?php echo esc_url( $portfolio_url ) ?>"><span><?php echo esc_url( $portfolio_url ) ?></span></a></div>
<div class="portfolio-detail-content"><i class="fa fa-facebook"></i> <span><?php echo '<a href="esc_attr( $portfolio_rates )"></a>' ?></span></div>
</div>
</div>
</div>
</div>
</code></pre>
<p>Is there any plausible way to render that blank space usable?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 232499,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>Short answer: most probably there is.</p>\n\n<p>I would recommend you use a child theme to achieve this. You can then copy any of the parent theme's templates into your child theme and alter them as you like. In your case it's probably something like \"<code>single-portfolio.php</code>\" inside the templates folder of the theme. </p>\n\n<p>A good starting point for working with child themes is the <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">Child Theme page of the WordPress codex</a>.</p>\n"
},
{
"answer_id": 232500,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you create a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">shortcode</a> for this , it's much easier, standard and flexible.</p>\n"
}
] |
2016/07/18
|
[
"https://wordpress.stackexchange.com/questions/232498",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98478/"
] |
I am currently working on [this website](http://www.highereg.com/member-list/starr-mazer) which uses a Wordpress theme designed by one Themeforest author. As can be seen via the link and the following screenshot from the same page, the theme's Portfolio (Custom Post Type) utilises 8 columns for textual and any other data -- with 4 other other columns to its right used in rendering a meta-box.
[](https://i.stack.imgur.com/vJORp.png)
My issue is largely with the blank space under the meta-box. The page's design is such that while only a portion of those 4 columns are used for the box, the rest of that space beneath it goes unused.
I am looking to amend this design; I'd like to fit in other plugins (a Newsletter sign up box, for instance) below the meta-box in the space bordered in Orange and am unsure on what would be the best way to go about it.
The theme author is also unresponsive which rules out asking them about the same. The code used in the design of the pictured portion of the page is as follows --
```
<div class="large-12 medium-12 columns">
<h2 class="portfolio-detail-title"><?php the_title(); ?></h2>
</div>
<div class="portfolio-detail-left large-8 medium-8 columns">
<div class="portfolio-detail-text">
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
</div>
</div>
<div class="portfolio-detail-right large-4 medium-4 columns ">
<div class="portfolio-detail-inner">
<div class="portfolio-detail">
<div class="portfolio-detail-content"><i class="fa fa-tag"></i> <span><?php the_terms( get_the_ID(), 'portfolio_categories' ); ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-user"></i> <span><?php echo esc_attr( $portfolio_client ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-home"></i> <span><?php echo esc_attr( $portfolio_location ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-bookmark-o"></i> <span><?php echo esc_attr( $portfolio_skills ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-cogs gears"></i> <span><?php echo esc_attr( $portfolio_rates ) ?></span></div>
<div class="portfolio-detail-url"><i class="fa fa-chain"></i> <a href="<?php echo esc_url( $portfolio_url ) ?>"><span><?php echo esc_url( $portfolio_url ) ?></span></a></div>
<div class="portfolio-detail-content"><i class="fa fa-facebook"></i> <span><?php echo '<a href="esc_attr( $portfolio_rates )"></a>' ?></span></div>
</div>
</div>
</div>
</div>
```
Is there any plausible way to render that blank space usable?
Thank you.
|
Why don't you create a [shortcode](https://codex.wordpress.org/Shortcode_API) for this , it's much easier, standard and flexible.
|
232,513 |
<p>I want to use Pagination using ajax for custom post taxonomy.
Many of codes are tried by me but at the last I was failed. So,how can i use pagination using ajax without plugin?</p>
<p>When i am clicking on load more button then the post will load on the same page.</p>
<p><strong>post name:- project</strong></p>
<p><strong>taxonomy name:- framework</strong></p>
<p><strong><code>functions.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code> function wp_pagination() {
global $wp_query;
$big = 12345678;
$page_format = paginate_links(array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages,
'type' => 'array'
));
if (is_array($page_format)) {
$paged = ( get_query_var('paged') == 0 ) ? 1 :
get_query_var('paged');
// echo '<div><ul>';
// echo '<li><span>'. $paged . ' of ' . $wp_query->max_num_pages.'</span></li>';
echo "<center>";
foreach ($page_format as $page) {
echo " " . $page;
}
echo "</center>";
echo '</div>';
}
}
</code></pre>
|
[
{
"answer_id": 232711,
"author": "jayesh",
"author_id": 98495,
"author_profile": "https://wordpress.stackexchange.com/users/98495",
"pm_score": 4,
"selected": true,
"text": "<p>I had got the ans.</p>\n\n<p>First you have to add following code in your function.php to call ajax in your template**</p>\n\n<pre><code>add_action( 'wp_ajax_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' );\n\nadd_action( 'wp_ajax_nopriv_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' ); \n\nfunction cvf_demo_pagination_load_posts() {\n\n global $wpdb;\n // Set default variables\n $msg = '';\n\n if(isset($_POST['page'])){\n // Sanitize the received page \n $page = sanitize_text_field($_POST['page']);\n $cur_page = $page;\n $page -= 1;\n // Set the number of results to display\n $per_page = 3;\n $previous_btn = true;\n $next_btn = true;\n $first_btn = true;\n $last_btn = true;\n $start = $page * $per_page;\n\n // Set the table where we will be querying data\n $table_name = $wpdb->prefix . \"posts\";\n\n // Query the necessary posts\n $all_blog_posts = $wpdb->get_results($wpdb->prepare(\"\n SELECT * FROM \" . $table_name . \" WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d\", $start, $per_page ) );\n\n // At the same time, count the number of queried posts\n $count = $wpdb->get_var($wpdb->prepare(\"\n SELECT COUNT(ID) FROM \" . $table_name . \" WHERE post_type = 'post' AND post_status = 'publish'\", array() ) );\n\n /**\n * Use WP_Query:\n *\n $all_blog_posts = new WP_Query(\n array(\n 'post_type' => 'post',\n 'post_status ' => 'publish',\n 'orderby' => 'post_date',\n 'order' => 'DESC',\n 'posts_per_page' => $per_page,\n 'offset' => $start\n )\n );\n\n $count = new WP_Query(\n array(\n 'post_type' => 'post',\n 'post_status ' => 'publish',\n 'posts_per_page' => -1\n )\n );\n */\n\n // Loop into all the posts\n foreach($all_blog_posts as $key => $post): \n\n // Set the desired output into a variable\n $msg .= '\n <div class = \"col-md-12\"> \n <h2><a href=\"' . get_permalink($post->ID) . '\">' . $post->post_title . '</a></h2>\n <p>' . $post->post_excerpt . '</p>\n <p>' . $post->post_content . '</p>\n </div>';\n\n endforeach;\n\n // Optional, wrap the output into a container\n $msg = \"<div class='cvf-universal-content'>\" . $msg . \"</div><br class = 'clear' />\";\n\n // This is where the magic happens\n $no_of_paginations = ceil($count / $per_page);\n\n if ($cur_page >= 7) {\n $start_loop = $cur_page - 3;\n if ($no_of_paginations > $cur_page + 3)\n $end_loop = $cur_page + 3;\n else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {\n $start_loop = $no_of_paginations - 6;\n $end_loop = $no_of_paginations;\n } else {\n $end_loop = $no_of_paginations;\n }\n } else {\n $start_loop = 1;\n if ($no_of_paginations > 7)\n $end_loop = 7;\n else\n $end_loop = $no_of_paginations;\n }\n\n // Pagination Buttons logic \n $pag_container .= \"\n <div class='cvf-universal-pagination'>\n <ul>\";\n\n if ($first_btn && $cur_page > 1) {\n $pag_container .= \"<li p='1' class='active'>First</li>\";\n } else if ($first_btn) {\n $pag_container .= \"<li p='1' class='inactive'>First</li>\";\n }\n\n if ($previous_btn && $cur_page > 1) {\n $pre = $cur_page - 1;\n $pag_container .= \"<li p='$pre' class='active'>Previous</li>\";\n } else if ($previous_btn) {\n $pag_container .= \"<li class='inactive'>Previous</li>\";\n }\n for ($i = $start_loop; $i <= $end_loop; $i++) {\n\n if ($cur_page == $i)\n $pag_container .= \"<li p='$i' class = 'selected' >{$i}</li>\";\n else\n $pag_container .= \"<li p='$i' class='active'>{$i}</li>\";\n }\n\n if ($next_btn && $cur_page < $no_of_paginations) {\n $nex = $cur_page + 1;\n $pag_container .= \"<li p='$nex' class='active'>Next</li>\";\n } else if ($next_btn) {\n $pag_container .= \"<li class='inactive'>Next</li>\";\n }\n\n if ($last_btn && $cur_page < $no_of_paginations) {\n $pag_container .= \"<li p='$no_of_paginations' class='active'>Last</li>\";\n } else if ($last_btn) {\n $pag_container .= \"<li p='$no_of_paginations' class='inactive'>Last</li>\";\n }\n\n $pag_container = $pag_container . \"\n </ul>\n </div>\";\n\n // We echo the final output\n echo \n '<div class = \"cvf-pagination-content\">' . $msg . '</div>' . \n '<div class = \"cvf-pagination-nav\">' . $pag_container . '</div>';\n\n }\n // Always exit to avoid further execution\n exit();}\n</code></pre>\n\n<p>Now add this following code where you want to display your post.(like,index.php,home.php,etc..)</p>\n\n<pre><code><div class=\"col-md-12 content\">\n <div class = \"inner-box content no-right-margin darkviolet\">\n <script type=\"text/javascript\">\n jQuery(document).ready(function($) {\n // This is required for AJAX to work on our page\n var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';\n\n function cvf_load_all_posts(page){\n // Start the transition\n $(\".cvf_pag_loading\").fadeIn().css('background','#ccc');\n\n // Data to receive from our server\n // the value in 'action' is the key that will be identified by the 'wp_ajax_' hook \n var data = {\n page: page,\n action: \"demo-pagination-load-posts\"\n };\n\n // Send the data\n $.post(ajaxurl, data, function(response) {\n // If successful Append the data into our html container\n $(\".cvf_universal_container\").append(response);\n // End the transition\n $(\".cvf_pag_loading\").css({'background':'none', 'transition':'all 1s ease-out'});\n });\n }\n\n // Load page 1 as the default\n cvf_load_all_posts(1);\n\n // Handle the clicks\n $('.cvf_universal_container .cvf-universal-pagination li.active').live('click',function(){\n var page = $(this).attr('p');\n cvf_load_all_posts(page);\n\n });\n\n }); \n </script>\n <div class = \"cvf_pag_loading\">\n <div class = \"cvf_universal_container\">\n <div class=\"cvf-universal-content\"></div>\n </div>\n </div>\n\n </div> \n</div>\n</code></pre>\n\n<p>And at the last put this code into your style.css</p>\n\n<pre><code>.cvf_pag_loading {padding: 20px;}\n.cvf-universal-pagination ul {margin: 0; padding: 0;}\n.cvf-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }\n.cvf-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }\n.cvf-universal-pagination ul li.inactive {background: #7E7E7E;}\n.cvf-universal-pagination ul li.selected {background: #1E8CBE; color: white;}\n</code></pre>\n\n<p>At the last you will see like this.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eFu2O.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eFu2O.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 346323,
"author": "Mohan",
"author_id": 102069,
"author_profile": "https://wordpress.stackexchange.com/users/102069",
"pm_score": 0,
"selected": false,
"text": "<p>I really appreciate the Pieter Goosen's efforts.</p>\n\n<p>Its now appending every response to same element and not removing older data as its pagination not ajax load more..Make changed as per below :</p>\n\n<pre><code>//$(\".cvf_universal_container\").append(response);\n$(\".cvf_universal_container\").empty().append(response);\n</code></pre>\n"
},
{
"answer_id": 403387,
"author": "Fanky",
"author_id": 89973,
"author_profile": "https://wordpress.stackexchange.com/users/89973",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Using native <code>paginate_links()</code></strong> (but working around the links):</p>\n<p><strong>your jQuery script</strong></p>\n<pre><code>jQuery( document ).on("click", ".page-numbers", function(e) {\n e.preventDefault();\n // prepare the number from "href" for ajax\n var formdata=$("#yourform").serialize() \n + "&action=yourajaxaction&pagenum=" + this.attr("href").replace("#","");\n\n //do the ajax\n $.post( ajaxurl, formdata, function( response ) {\n $("#ajaxcont").html(response);\n });\n</code></pre>\n<p><strong>in your ajax function</strong></p>\n<pre><code> // get the page number\n $args["paged"]=(int)$_POST["pagenum"];\n\n // ... process query with $args ...\n \n //output pagination \n echo paginate_links( array(\n 'total' => $thaquery->max_num_pages,\n 'current' => $thaargs["paged"],\n 'base' => "#%#%" //will make hrefs like "#3"\n ) );\n</code></pre>\n"
}
] |
2016/07/18
|
[
"https://wordpress.stackexchange.com/questions/232513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98495/"
] |
I want to use Pagination using ajax for custom post taxonomy.
Many of codes are tried by me but at the last I was failed. So,how can i use pagination using ajax without plugin?
When i am clicking on load more button then the post will load on the same page.
**post name:- project**
**taxonomy name:- framework**
**`functions.php`**
```php
function wp_pagination() {
global $wp_query;
$big = 12345678;
$page_format = paginate_links(array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages,
'type' => 'array'
));
if (is_array($page_format)) {
$paged = ( get_query_var('paged') == 0 ) ? 1 :
get_query_var('paged');
// echo '<div><ul>';
// echo '<li><span>'. $paged . ' of ' . $wp_query->max_num_pages.'</span></li>';
echo "<center>";
foreach ($page_format as $page) {
echo " " . $page;
}
echo "</center>";
echo '</div>';
}
}
```
|
I had got the ans.
First you have to add following code in your function.php to call ajax in your template\*\*
```
add_action( 'wp_ajax_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' );
add_action( 'wp_ajax_nopriv_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' );
function cvf_demo_pagination_load_posts() {
global $wpdb;
// Set default variables
$msg = '';
if(isset($_POST['page'])){
// Sanitize the received page
$page = sanitize_text_field($_POST['page']);
$cur_page = $page;
$page -= 1;
// Set the number of results to display
$per_page = 3;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
// Set the table where we will be querying data
$table_name = $wpdb->prefix . "posts";
// Query the necessary posts
$all_blog_posts = $wpdb->get_results($wpdb->prepare("
SELECT * FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page ) );
// At the same time, count the number of queried posts
$count = $wpdb->get_var($wpdb->prepare("
SELECT COUNT(ID) FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish'", array() ) );
/**
* Use WP_Query:
*
$all_blog_posts = new WP_Query(
array(
'post_type' => 'post',
'post_status ' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'offset' => $start
)
);
$count = new WP_Query(
array(
'post_type' => 'post',
'post_status ' => 'publish',
'posts_per_page' => -1
)
);
*/
// Loop into all the posts
foreach($all_blog_posts as $key => $post):
// Set the desired output into a variable
$msg .= '
<div class = "col-md-12">
<h2><a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a></h2>
<p>' . $post->post_excerpt . '</p>
<p>' . $post->post_content . '</p>
</div>';
endforeach;
// Optional, wrap the output into a container
$msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";
// This is where the magic happens
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
// Pagination Buttons logic
$pag_container .= "
<div class='cvf-universal-pagination'>
<ul>";
if ($first_btn && $cur_page > 1) {
$pag_container .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$pag_container .= "<li p='1' class='inactive'>First</li>";
}
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$pag_container .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$pag_container .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
else
$pag_container .= "<li p='$i' class='active'>{$i}</li>";
}
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$pag_container .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$pag_container .= "<li class='inactive'>Next</li>";
}
if ($last_btn && $cur_page < $no_of_paginations) {
$pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$pag_container = $pag_container . "
</ul>
</div>";
// We echo the final output
echo
'<div class = "cvf-pagination-content">' . $msg . '</div>' .
'<div class = "cvf-pagination-nav">' . $pag_container . '</div>';
}
// Always exit to avoid further execution
exit();}
```
Now add this following code where you want to display your post.(like,index.php,home.php,etc..)
```
<div class="col-md-12 content">
<div class = "inner-box content no-right-margin darkviolet">
<script type="text/javascript">
jQuery(document).ready(function($) {
// This is required for AJAX to work on our page
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
function cvf_load_all_posts(page){
// Start the transition
$(".cvf_pag_loading").fadeIn().css('background','#ccc');
// Data to receive from our server
// the value in 'action' is the key that will be identified by the 'wp_ajax_' hook
var data = {
page: page,
action: "demo-pagination-load-posts"
};
// Send the data
$.post(ajaxurl, data, function(response) {
// If successful Append the data into our html container
$(".cvf_universal_container").append(response);
// End the transition
$(".cvf_pag_loading").css({'background':'none', 'transition':'all 1s ease-out'});
});
}
// Load page 1 as the default
cvf_load_all_posts(1);
// Handle the clicks
$('.cvf_universal_container .cvf-universal-pagination li.active').live('click',function(){
var page = $(this).attr('p');
cvf_load_all_posts(page);
});
});
</script>
<div class = "cvf_pag_loading">
<div class = "cvf_universal_container">
<div class="cvf-universal-content"></div>
</div>
</div>
</div>
</div>
```
And at the last put this code into your style.css
```
.cvf_pag_loading {padding: 20px;}
.cvf-universal-pagination ul {margin: 0; padding: 0;}
.cvf-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
.cvf-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
.cvf-universal-pagination ul li.inactive {background: #7E7E7E;}
.cvf-universal-pagination ul li.selected {background: #1E8CBE; color: white;}
```
At the last you will see like this.
[](https://i.stack.imgur.com/eFu2O.png)
|
232,527 |
<p>I have set up a fresh installation of WordPress 4.5.3 and activated the Multisite feature, following all the instructions required to activate it.</p>
<p>I added a second site, and once it was created I tried clicking on the dashboard for the second site but it directs me to the first site dashboard, everytime!</p>
<p>I tried to visit the second link I made - for instance <code>www.example.com/ar</code> - and it shows the website without the theme and with the wrong links. Again I try to go back and edit it; again it redirects me to the main site.</p>
<p>What can I do to resolve this?</p>
<p>My domain is registered through GoDaddy.</p>
|
[
{
"answer_id": 232571,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you've set up your rewrite rules in your <code>.htaccess</code> file. The Multisite rules are different from the default WordPress rules.</p>\n\n<p>If this is an up-to-date version of WordPress, your <code>.htaccess</code> rewrite rules should look like this:</p>\n\n<h2>Subdirectory</h2>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\n\n# add a trailing slash to /wp-admin\nRewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]\n\nRewriteCond %{REQUEST_FILENAME} -f [OR]\nRewriteCond %{REQUEST_FILENAME} -d\nRewriteRule ^ - [L]\nRewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]\nRewriteRule ^([_0-9a-zA-Z-]+/)?(.*\\.php)$ $2 [L]\nRewriteRule . index.php [L]\n</code></pre>\n\n<h2>Subdomain</h2>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\n\n# add a trailing slash to /wp-admin\nRewriteRule ^wp-admin$ wp-admin/ [R=301,L]\n\nRewriteCond %{REQUEST_FILENAME} -f [OR]\nRewriteCond %{REQUEST_FILENAME} -d\nRewriteRule ^ - [L]\nRewriteRule ^(wp-(content|admin|includes).*) $1 [L]\nRewriteRule ^(.*\\.php)$ $1 [L]\nRewriteRule . index.php [L]\n</code></pre>\n\n<p>See the <a href=\"https://codex.wordpress.org/htaccess\" rel=\"nofollow\">Codex page on <code>.htaccess</code></a> for more details.</p>\n"
},
{
"answer_id": 296470,
"author": "kevinweber",
"author_id": 46101,
"author_profile": "https://wordpress.stackexchange.com/users/46101",
"pm_score": 0,
"selected": false,
"text": "<p>I assume that the culprit here is GoDaddy. It looks like the GoDaddy setup prevents users from editing the Siteurl and Home URL setting of a site in a multisite network. You can try to customize the URL but the change doesn't get saved:</p>\n\n<p><a href=\"https://i.stack.imgur.com/FOnez.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FOnez.png\" alt=\"Can't save Siteurl with GoDaddy in Multisite network\"></a></p>\n\n<p>The only solution I found so far is to manually update both values in the database. Once you've accessed the database, look for a table <code>wp_SOMETEXT_2_options</code> (\"2\" is the ID of your site in the multisite network), browse it and update the <code>option_value</code> cells:</p>\n\n<p><a href=\"https://i.stack.imgur.com/waao8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/waao8.png\" alt=\"Manually update Siteurl in GoDaddy database\"></a></p>\n\n<p>Once you've updated those cells, the updated Siteurl and Home URL should now be displayed in the settings tab in your WordPress backend. Additionally, make sure that the Site Address is up-to-date. You should be able to update the Site Address from the WordPress backend:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Z3jvp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z3jvp.png\" alt=\"Update site address in GoDaddy WordPress site\"></a></p>\n"
}
] |
2016/07/18
|
[
"https://wordpress.stackexchange.com/questions/232527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98503/"
] |
I have set up a fresh installation of WordPress 4.5.3 and activated the Multisite feature, following all the instructions required to activate it.
I added a second site, and once it was created I tried clicking on the dashboard for the second site but it directs me to the first site dashboard, everytime!
I tried to visit the second link I made - for instance `www.example.com/ar` - and it shows the website without the theme and with the wrong links. Again I try to go back and edit it; again it redirects me to the main site.
What can I do to resolve this?
My domain is registered through GoDaddy.
|
Make sure you've set up your rewrite rules in your `.htaccess` file. The Multisite rules are different from the default WordPress rules.
If this is an up-to-date version of WordPress, your `.htaccess` rewrite rules should look like this:
Subdirectory
------------
```
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
```
Subdomain
---------
```
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
```
See the [Codex page on `.htaccess`](https://codex.wordpress.org/htaccess) for more details.
|
232,600 |
<p>I'm trying to get the <code>current-menu-item-id</code> in any page.
I have used <a href="https://wordpress.stackexchange.com/questions/16243/how-to-get-current-menu-item-title-as-variable">this solution</a>, that brings me very close to the solution.</p>
<p>The problem I have is, that the function below is going through all the menus on the page, and not only the one specific menu, that I want it to go through:</p>
<pre><code>add_filter( 'wp_nav_menu_objects', 'wpse16243_wp_nav_menu_objects' );
function wpse16243_wp_nav_menu_objects( $sorted_menu_items )
{
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
$GLOBALS['wpse16243_title'] = $menu_item->ID;
}
}
return $sorted_menu_items;
}
</code></pre>
<p>...which means that if you link to the same page more than once in your menus, you can risk that this function returns the <code>current-menu-item-id</code> from the wrong menu.</p>
<p>Is there any way that I can limit this function to <strong>only</strong> go through a specific menu and not all menus?
I tried to pass the specific menu items in the variable/parameter <code>$sorted_menu_items</code>, but that seems not to work.</p>
|
[
{
"answer_id": 232581,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 4,
"selected": true,
"text": "<p>Yes!</p>\n\n<ol>\n<li>Go to your Media Library </li>\n<li>Find the Image </li>\n<li>Click Edit </li>\n<li>Locate the Permalink under the Title </li>\n<li>Click Edit </li>\n<li>Change the Permalink </li>\n<li>Click Update!</li>\n</ol>\n\n<h2>Edit</h2>\n\n<p>If for some reason you cannot Edit the Images' Permalink... you could:</p>\n\n<ol>\n<li>Delete Image</li>\n<li>Change your Pages' Permalink</li>\n<li>Re-Upload Image</li>\n</ol>\n"
},
{
"answer_id": 283456,
"author": "Devin Peterson",
"author_id": 129930,
"author_profile": "https://wordpress.stackexchange.com/users/129930",
"pm_score": 6,
"selected": false,
"text": "<ol>\n<li>Go to Media Library</li>\n<li>Find the Image</li>\n<li>Click Edit Image</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/VFwjF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VFwjF.png\" alt=\"\"></a></p>\n\n<ol start=\"4\">\n<li>Click Edit more details (at bottom right, very easy to miss)</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/Ctfew.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Ctfew.png\" alt=\"\"></a> </p>\n\n<ol start=\"5\">\n<li>Find the Screen Options (top right) and enable the Slug checkbox</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/agYKu.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/agYKu.png\" alt=\"\"></a></p>\n\n<ol start=\"6\">\n<li>Scroll down to the slug box and change the slug to whatever you want. </li>\n<li>Click Update!</li>\n</ol>\n"
},
{
"answer_id": 286352,
"author": "Andy",
"author_id": 131751,
"author_profile": "https://wordpress.stackexchange.com/users/131751",
"pm_score": 3,
"selected": false,
"text": "<p>In Media Library, I noticed that when media file is not Attached to a page the permalink is not editable. When they are attached, permalink editing is permitted.</p>\n"
},
{
"answer_id": 288652,
"author": "Brock Deskins",
"author_id": 133320,
"author_profile": "https://wordpress.stackexchange.com/users/133320",
"pm_score": 3,
"selected": false,
"text": "<p>On the edit page, \n1. click the screen options downward triangle in the upper right of the screen\n2. Check \"Slug\" under Boxes.\n3. Update\n4. Scroll down to Slug box.\n5. Type in what you want to call the link.</p>\n\n<p>This doesn't change the link location. Just the link name, which is what I was trying to figure out since I didn't want it as the name of the file I uploaded.</p>\n"
}
] |
2016/07/19
|
[
"https://wordpress.stackexchange.com/questions/232600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97806/"
] |
I'm trying to get the `current-menu-item-id` in any page.
I have used [this solution](https://wordpress.stackexchange.com/questions/16243/how-to-get-current-menu-item-title-as-variable), that brings me very close to the solution.
The problem I have is, that the function below is going through all the menus on the page, and not only the one specific menu, that I want it to go through:
```
add_filter( 'wp_nav_menu_objects', 'wpse16243_wp_nav_menu_objects' );
function wpse16243_wp_nav_menu_objects( $sorted_menu_items )
{
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
$GLOBALS['wpse16243_title'] = $menu_item->ID;
}
}
return $sorted_menu_items;
}
```
...which means that if you link to the same page more than once in your menus, you can risk that this function returns the `current-menu-item-id` from the wrong menu.
Is there any way that I can limit this function to **only** go through a specific menu and not all menus?
I tried to pass the specific menu items in the variable/parameter `$sorted_menu_items`, but that seems not to work.
|
Yes!
1. Go to your Media Library
2. Find the Image
3. Click Edit
4. Locate the Permalink under the Title
5. Click Edit
6. Change the Permalink
7. Click Update!
Edit
----
If for some reason you cannot Edit the Images' Permalink... you could:
1. Delete Image
2. Change your Pages' Permalink
3. Re-Upload Image
|
232,610 |
<p>I have the following code:-</p>
<pre><code><!-- News Archive -->
<div id="news-archive">
<div class="row">
<div class="col-md-12">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'cat' => '8',
'offset' => 2,
'posts_per_page' => 6,
'paged' => $paged
);
$loop = new WP_Query($args);
$post_counter = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-xs-12 col-sm-4 col-md-4">
<div id="blog-<?php echo $post_counter; ?>" class="blog-wrapper">
<?php if(get_the_post_thumbnail()) {
the_post_thumbnail();
} else {
$category = "/wp-content/themes/irongate/assets/img/" . get_field('group_category') . '-default.jpg'; ?>
<img src="<?php echo $category; ?>" />
<?php } ?>
<span class="news-archive-date"><?php echo get_the_date('d M Y'); ?></span>
<p class="news-archive-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<span id="<?php echo $case_category; ?>-logo" class="<?php echo get_field('group_category') == 'inone' ? 'inone-catergory' : 'news-archive-catergory';?>"></span>
<a href="<?php the_permalink(); ?>">
<div class="news-overlay blog-overlay">
<span class="news-overlay-excerpt"><?php echo substr(get_the_excerpt(), 0,240); ?>...</span>
<span id="careers-overlay-more" class="btn-white">Read more</span>
</div>
</a>
</div>
</div>
<?php if($post_counter % 3 == 0) {echo '<div class="clearfix"></div>';}
$post_counter++;
endwhile; ?><!-- News Archive -->
<div class="navigation">
<div class="alignleft"><?php previous_posts_link('&laquo; Previous') ?></div>
<div class="alignright"><?php next_posts_link('More &raquo;') ?></div>
</div>
<?php wp_reset_postdata(); ?>
</div>
</div>
</div>
</code></pre>
<p>The display of the posts is showing correctly as 6 blog posts and the 'More...' button appears but when clicked it just reloads the same content.</p>
<p>How can I add pagination to my blog posts? i.e. clicking next... will show posts 9-14 instead of 2-8 (as I'm using an offset of 2).</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 232970,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 3,
"selected": true,
"text": "<p>You can calculate <code>offset</code> via <code>paged</code> and <code>posts_per_page</code>. E.g:</p>\n\n<pre><code>$per_page = 6;\n$paged = get_query_var('paged') ? : 1;\n$offset = (1 === $paged) ? 0 : (($paged - 1) * $per_page) + (($paged - 1) * 2);\n\n$args = array(\n 'order' => 'ASC',\n 'paged' => $paged,\n 'offset' => $offset,\n 'orderby' => 'ID',\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page' => $per_page,\n 'ignore_sticky_posts' => 1\n);\n\n$query = new WP_Query($args);\n\nwhile ( $query->have_posts() ) : $query->the_post();\n echo get_the_title() . '<br>';\nendwhile;\n\nprevious_posts_link('&laquo; Previous', $query->max_num_pages);\nif ($paged > 1) echo ' | ';\nnext_posts_link('More &raquo;', $query->max_num_pages);\n\necho '<br> Showing ' . $offset . '-' . ($offset + 6) . ' of ' . $query->found_posts . ' posts.';\n\nwp_reset_postdata();\n</code></pre>\n\n<p>Note that the loop start at index 0, so if we ignore sticky posts and only display 6 posts per page, the result on page 2 should be 8-14 instead 9-14 as you expected.</p>\n"
},
{
"answer_id": 232999,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 0,
"selected": false,
"text": "<p>Or you can use paginate_links:</p>\n\n<pre><code>//First get a count of how many pages you'll be producing:\n\n$cat_id = 8;\n$per_page = 6;\n\n$all_posts = get_term_by( 'id', $cat_id, 'category' );\n$posts_count = $all_posts->count ;\n$total_pages = intval( $posts_count / $per_page ) + 1;\n\n$current_page = max(1, get_query_var( 'paged' ) );\n\necho '<div class=\"pagination\">' ;\n\necho paginate_links(array(\n //several different ways to do the base variable in my observation/experience\n 'base' => get_pagenum_link(1) . '%_%',\n 'current' => $current_page,\n 'total' => $total_pages,\n //if you like the double arrow (Euro quotes) format\n 'prev_text' => '&laquo; Previous',\n 'next_text' => 'Next &raquo;' \n) );\n\necho '</div>' ;\n</code></pre>\n\n<p>Some variations may be required depending on your permalinks style, and you can find a lot of interesting formatting for the links themselves based on available parameters and standard or customized output, but I think this should answer the basic question. See ttps://codex.wordpress.org/Function_Reference/paginate_links for other basic examples. </p>\n"
},
{
"answer_id": 233078,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 1,
"selected": false,
"text": "<p>If you are useing <a href=\"https://codex.wordpress.org/Function_Reference/next_posts_link\" rel=\"nofollow noreferrer\">next_posts_link()</a> && <a href=\"https://codex.wordpress.org/Function_Reference/previous_posts_link\" rel=\"nofollow noreferrer\">previous_posts_link()</a> on your custom Query then you have to pass $max_pages parameter. like -></p>\n\n<pre><code>previous_posts_link( '&laquo; Previous', $loop->max_num_pages );\nnext_posts_link( '&laquo; Previous', $loop->max_num_pages );\n</code></pre>\n\n<p>Or if you want to use just previous_posts_link( '« Previous'); without useing $max_pages parameter then you have to use default query instead custom query. And it's better to used default one. see more details <a href=\"https://wordpress.stackexchange.com/questions/50761/when-to-use-wp-query-query-posts-and-pre-get-posts\">When to use WP_query(), query_posts() and pre_get_posts</a></p>\n"
}
] |
2016/07/19
|
[
"https://wordpress.stackexchange.com/questions/232610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81966/"
] |
I have the following code:-
```
<!-- News Archive -->
<div id="news-archive">
<div class="row">
<div class="col-md-12">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'cat' => '8',
'offset' => 2,
'posts_per_page' => 6,
'paged' => $paged
);
$loop = new WP_Query($args);
$post_counter = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-xs-12 col-sm-4 col-md-4">
<div id="blog-<?php echo $post_counter; ?>" class="blog-wrapper">
<?php if(get_the_post_thumbnail()) {
the_post_thumbnail();
} else {
$category = "/wp-content/themes/irongate/assets/img/" . get_field('group_category') . '-default.jpg'; ?>
<img src="<?php echo $category; ?>" />
<?php } ?>
<span class="news-archive-date"><?php echo get_the_date('d M Y'); ?></span>
<p class="news-archive-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<span id="<?php echo $case_category; ?>-logo" class="<?php echo get_field('group_category') == 'inone' ? 'inone-catergory' : 'news-archive-catergory';?>"></span>
<a href="<?php the_permalink(); ?>">
<div class="news-overlay blog-overlay">
<span class="news-overlay-excerpt"><?php echo substr(get_the_excerpt(), 0,240); ?>...</span>
<span id="careers-overlay-more" class="btn-white">Read more</span>
</div>
</a>
</div>
</div>
<?php if($post_counter % 3 == 0) {echo '<div class="clearfix"></div>';}
$post_counter++;
endwhile; ?><!-- News Archive -->
<div class="navigation">
<div class="alignleft"><?php previous_posts_link('« Previous') ?></div>
<div class="alignright"><?php next_posts_link('More »') ?></div>
</div>
<?php wp_reset_postdata(); ?>
</div>
</div>
</div>
```
The display of the posts is showing correctly as 6 blog posts and the 'More...' button appears but when clicked it just reloads the same content.
How can I add pagination to my blog posts? i.e. clicking next... will show posts 9-14 instead of 2-8 (as I'm using an offset of 2).
Thanks in advance!
|
You can calculate `offset` via `paged` and `posts_per_page`. E.g:
```
$per_page = 6;
$paged = get_query_var('paged') ? : 1;
$offset = (1 === $paged) ? 0 : (($paged - 1) * $per_page) + (($paged - 1) * 2);
$args = array(
'order' => 'ASC',
'paged' => $paged,
'offset' => $offset,
'orderby' => 'ID',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $per_page,
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
while ( $query->have_posts() ) : $query->the_post();
echo get_the_title() . '<br>';
endwhile;
previous_posts_link('« Previous', $query->max_num_pages);
if ($paged > 1) echo ' | ';
next_posts_link('More »', $query->max_num_pages);
echo '<br> Showing ' . $offset . '-' . ($offset + 6) . ' of ' . $query->found_posts . ' posts.';
wp_reset_postdata();
```
Note that the loop start at index 0, so if we ignore sticky posts and only display 6 posts per page, the result on page 2 should be 8-14 instead 9-14 as you expected.
|
232,663 |
<p>I am trying to post to WordPress using the REST API. The aim is to have a form that accepts The following information:</p>
<ul>
<li>Title</li>
<li>Content</li>
<li>ACF Custom Field 1 (possibly repeater field)</li>
<li>ACF Custom Field 2 (possibly repeater field)</li>
<li>Featured Image</li>
</ul>
<p>I am new to the WP API and am having some difficulty finding some solid documentation on how I could post to a WP site from an external page/site that is not WordPress. </p>
<p>The idea is that users of website 'a' can fill out a form and this create a post on website 'b'. </p>
<p>I am not sure on user authentication as of yet so will either post annonymously or with a single user account.</p>
<p>Is anyone able to show me a simple method showing a basic outline of the above using Javascript or point me in the right direction atleast as I have found the docs a little confusing.</p>
|
[
{
"answer_id": 232664,
"author": "whakawaehere",
"author_id": 78660,
"author_profile": "https://wordpress.stackexchange.com/users/78660",
"pm_score": -1,
"selected": false,
"text": "<p>I think the simplest solution, without having more details about site A or site B, would be to use a service like Zapier to make your connection.</p>\n"
},
{
"answer_id": 383024,
"author": "RocketMan",
"author_id": 198263,
"author_profile": "https://wordpress.stackexchange.com/users/198263",
"pm_score": 1,
"selected": false,
"text": "<p>To answer your broader question about resources - while there are many articles out there, I would always recommend checking out the official <a href=\"https://developer.wordpress.org/rest-api/reference/posts/\" rel=\"nofollow noreferrer\">WordPress API Handbook</a> first.</p>\n<p>You first have to decide which JavaScript library you want to use to make HTTP requests to access the REST API. Axios is one example.</p>\n<p>To set the featured image, you first have to uploaded it as media (which you can do via the REST API) and then include the media id in the post request (more details below).</p>\n<p>Then to create the post via the REST API, you would make a <code>POST</code> HTTP request to <code>https:/<your-site>/wp-json/wp/v2/posts</code> with a body like:</p>\n<pre><code>{\n content: 'My post content here',\n title: 'Post Title',\n featured_media: [image-media-id],\n status: 'publish' // or 'draft'\n}\n</code></pre>\n<p>To get the ACF Custom Fields accessible/editable via the REST API, check out this plugin: <a href=\"https://github.com/airesvsg/acf-to-rest-api/\" rel=\"nofollow noreferrer\">https://github.com/airesvsg/acf-to-rest-api/</a>. I haven't used it yet, but it seems like what you're looking for.</p>\n<p>Also be aware that if site 'a' is on a different domain than site 'b', you may have <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\" rel=\"nofollow noreferrer\">CORS</a> issues to deal with as well. WordPress has good guides for dealing with that.</p>\n"
}
] |
2016/07/19
|
[
"https://wordpress.stackexchange.com/questions/232663",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64567/"
] |
I am trying to post to WordPress using the REST API. The aim is to have a form that accepts The following information:
* Title
* Content
* ACF Custom Field 1 (possibly repeater field)
* ACF Custom Field 2 (possibly repeater field)
* Featured Image
I am new to the WP API and am having some difficulty finding some solid documentation on how I could post to a WP site from an external page/site that is not WordPress.
The idea is that users of website 'a' can fill out a form and this create a post on website 'b'.
I am not sure on user authentication as of yet so will either post annonymously or with a single user account.
Is anyone able to show me a simple method showing a basic outline of the above using Javascript or point me in the right direction atleast as I have found the docs a little confusing.
|
To answer your broader question about resources - while there are many articles out there, I would always recommend checking out the official [WordPress API Handbook](https://developer.wordpress.org/rest-api/reference/posts/) first.
You first have to decide which JavaScript library you want to use to make HTTP requests to access the REST API. Axios is one example.
To set the featured image, you first have to uploaded it as media (which you can do via the REST API) and then include the media id in the post request (more details below).
Then to create the post via the REST API, you would make a `POST` HTTP request to `https:/<your-site>/wp-json/wp/v2/posts` with a body like:
```
{
content: 'My post content here',
title: 'Post Title',
featured_media: [image-media-id],
status: 'publish' // or 'draft'
}
```
To get the ACF Custom Fields accessible/editable via the REST API, check out this plugin: <https://github.com/airesvsg/acf-to-rest-api/>. I haven't used it yet, but it seems like what you're looking for.
Also be aware that if site 'a' is on a different domain than site 'b', you may have [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) issues to deal with as well. WordPress has good guides for dealing with that.
|
232,675 |
<p>I am trying to figure out how to add user information and specific meta data to a separate table through PHP. I would prefer to do this when a user posted to the <code>wp_users</code> and <code>wp_usermeta</code> table. I am using the WooCommerce Auction plugin and the Salient theme.</p>
<p>Also if I made a PHP file that ran a query to pull the data and then insert, where is a good place I can call that function to ensure the table is up to date?</p>
<p>This is the function I've created.</p>
<pre><code>add_action('user_register', 'save_to_donors',10,1);
function save_to_donors( $user_id ) {
$single = true;
$user_email = get_userdata($user_id);
$fn= get_user_meta($user_id, 'first_ name', $single );
$ln= get_user_meta($user_id, 'last_name', $single );
$em= $user_email->user_email;
$ph= get_user_meta($user_id, 'billing_phone', $single );
$ad= get_user_meta($user_id, 'billing_address_1', $single );
$ci= get_user_meta($user_id, 'billing_city', $single );
$st= get_user_meta($user_id, 'billing_state', $single );
$zi= get_user_meta($user_id, 'billing_postcode',$single );
$do= get_user_meta($user_id, '_money_spent', $single );
$sql = "INSERT INTO donors (user_id,first_name,last_name,email," .
"phone,address,city,state,zip,amount_donated)".
"VALUES('$user_id','$fn','$ln','$em','$ph','$ad','$ci','$st','$zi','$do')";
$result = mysqli_query($wpdb, $sql) or die('Write Error!');
}
</code></pre>
|
[
{
"answer_id": 232685,
"author": "stoi2m1",
"author_id": 10907,
"author_profile": "https://wordpress.stackexchange.com/users/10907",
"pm_score": 0,
"selected": false,
"text": "<p><strong>NOTE:</strong> This answer looks irrelevant to the OP's question after further analysis of the added/updated function in the question. Im leaving this answer in place and creating a new answer for historical use, since part of the question seems applicable.</p>\n\n<p>You could use something like the following to create user meta when users are added to the user table. Put this in the functions.php file of your theme.</p>\n\n<pre><code>function myplugin_registration_save( $user_id ) {\n\n if ( isset( $_POST['first_name'] ) )\n update_user_meta(\n $user_id, \n 'your_key', // name of key \n $your_value // value of your key\n );\n\n}\nadd_action( 'user_register', 'myplugin_registration_save', 10, 1 );\n</code></pre>\n\n<p>To retrieve this data for later use use the function:</p>\n\n<pre><code>get_user_meta($user_id, 'your_key', $single);\n</code></pre>\n\n<p>More info on <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\">user_register hook</a>\nMore info on <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow\">update_user_meta()</a>\nMore info on <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\">get_user_meta()</a></p>\n"
},
{
"answer_id": 232691,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 1,
"selected": false,
"text": "<p>This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.</p>\n\n<p>Not all user meta data has been stored in the database when this action is triggered. For example, nickname is in the database but first_name and last_name. The password has already been encrypted when this action is triggered.</p>\n\n<p>Typically, this hook is used for saving additional user meta passed by custom registration forms. </p>\n\n<p>This example will save a first_name field passed by a custom registration field.</p>\n\n<p>Also, keep in mind that validation of registration fields should not be performed within this hook! Validate using the registration_errors hook, instead (the user_register hook will not be called if registration_errors validation fails). </p>\n\n<pre><code>add_action( 'user_register', 'myplugin_registration_save', 10, 1 );\n\nfunction myplugin_registration_save( $user_id ) {\n\n if ( isset( $_POST['first_name'] ) )\n update_user_meta($user_id, 'first_name', $_POST['first_name']);\n\n}\n</code></pre>\n"
},
{
"answer_id": 232787,
"author": "stoi2m1",
"author_id": 10907,
"author_profile": "https://wordpress.stackexchange.com/users/10907",
"pm_score": 2,
"selected": true,
"text": "<p>Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table.</p>\n\n<p>use this:</p>\n\n<pre><code>add_action('woocommerce_order_status_completed', 'save_to_donors',10,1);\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>add_action('user_register', 'save_to_donors',10,1);\n</code></pre>\n\n<p>also change <code>$user_id</code> to <code>$order_id</code> as the parameter being passed into your function.</p>\n\n<p>You will need to make some changes to your function since now <code>$order_id</code> will be passed into your function instead of <code>$user_id</code>. You can use some of the following code to get the <code>$order</code> object and <code>$user_id</code> I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different.</p>\n\n<pre><code>$order = new WC_Order( $order_id );\n$user_id = $order->user_id;\n$billing_address = $order->get_billing_address();\n$billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page\n$shipping_address = $order->get_shipping_address();\n$shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page\n</code></pre>\n\n<p>Info on the use of this hook <a href=\"http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/\" rel=\"nofollow noreferrer\">woocommerce_order_status_completed</a><br>\nInfo on how to <a href=\"https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce\">get user id from order id</a></p>\n"
}
] |
2016/07/20
|
[
"https://wordpress.stackexchange.com/questions/232675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98590/"
] |
I am trying to figure out how to add user information and specific meta data to a separate table through PHP. I would prefer to do this when a user posted to the `wp_users` and `wp_usermeta` table. I am using the WooCommerce Auction plugin and the Salient theme.
Also if I made a PHP file that ran a query to pull the data and then insert, where is a good place I can call that function to ensure the table is up to date?
This is the function I've created.
```
add_action('user_register', 'save_to_donors',10,1);
function save_to_donors( $user_id ) {
$single = true;
$user_email = get_userdata($user_id);
$fn= get_user_meta($user_id, 'first_ name', $single );
$ln= get_user_meta($user_id, 'last_name', $single );
$em= $user_email->user_email;
$ph= get_user_meta($user_id, 'billing_phone', $single );
$ad= get_user_meta($user_id, 'billing_address_1', $single );
$ci= get_user_meta($user_id, 'billing_city', $single );
$st= get_user_meta($user_id, 'billing_state', $single );
$zi= get_user_meta($user_id, 'billing_postcode',$single );
$do= get_user_meta($user_id, '_money_spent', $single );
$sql = "INSERT INTO donors (user_id,first_name,last_name,email," .
"phone,address,city,state,zip,amount_donated)".
"VALUES('$user_id','$fn','$ln','$em','$ph','$ad','$ci','$st','$zi','$do')";
$result = mysqli_query($wpdb, $sql) or die('Write Error!');
}
```
|
Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table.
use this:
```
add_action('woocommerce_order_status_completed', 'save_to_donors',10,1);
```
instead of this:
```
add_action('user_register', 'save_to_donors',10,1);
```
also change `$user_id` to `$order_id` as the parameter being passed into your function.
You will need to make some changes to your function since now `$order_id` will be passed into your function instead of `$user_id`. You can use some of the following code to get the `$order` object and `$user_id` I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different.
```
$order = new WC_Order( $order_id );
$user_id = $order->user_id;
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page
```
Info on the use of this hook [woocommerce\_order\_status\_completed](http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/)
Info on how to [get user id from order id](https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce)
|
232,692 |
<p>I have to make several changes to a website, and I'm willing to setup a copy of the current one on a subdirectory, on the same server.</p>
<p>I.E. if my site is <code>www.example.com</code>, what I'm trying to do is to fully copy it to <code>www.example.com/new/</code>, make all the necessary modifications, then, once it is done, copy it back to the main directory.</p>
<p>I know that it is not a simple matter of moving files, I guess that this is a complex matter involving different file paths and database entries. I'd like to know how can I safely do it and it the whole process has to be done manually or if there are some automatic tools (i.e. plugins) that can help me doing it without mistakes.</p>
|
[
{
"answer_id": 232685,
"author": "stoi2m1",
"author_id": 10907,
"author_profile": "https://wordpress.stackexchange.com/users/10907",
"pm_score": 0,
"selected": false,
"text": "<p><strong>NOTE:</strong> This answer looks irrelevant to the OP's question after further analysis of the added/updated function in the question. Im leaving this answer in place and creating a new answer for historical use, since part of the question seems applicable.</p>\n\n<p>You could use something like the following to create user meta when users are added to the user table. Put this in the functions.php file of your theme.</p>\n\n<pre><code>function myplugin_registration_save( $user_id ) {\n\n if ( isset( $_POST['first_name'] ) )\n update_user_meta(\n $user_id, \n 'your_key', // name of key \n $your_value // value of your key\n );\n\n}\nadd_action( 'user_register', 'myplugin_registration_save', 10, 1 );\n</code></pre>\n\n<p>To retrieve this data for later use use the function:</p>\n\n<pre><code>get_user_meta($user_id, 'your_key', $single);\n</code></pre>\n\n<p>More info on <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\">user_register hook</a>\nMore info on <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow\">update_user_meta()</a>\nMore info on <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\">get_user_meta()</a></p>\n"
},
{
"answer_id": 232691,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 1,
"selected": false,
"text": "<p>This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.</p>\n\n<p>Not all user meta data has been stored in the database when this action is triggered. For example, nickname is in the database but first_name and last_name. The password has already been encrypted when this action is triggered.</p>\n\n<p>Typically, this hook is used for saving additional user meta passed by custom registration forms. </p>\n\n<p>This example will save a first_name field passed by a custom registration field.</p>\n\n<p>Also, keep in mind that validation of registration fields should not be performed within this hook! Validate using the registration_errors hook, instead (the user_register hook will not be called if registration_errors validation fails). </p>\n\n<pre><code>add_action( 'user_register', 'myplugin_registration_save', 10, 1 );\n\nfunction myplugin_registration_save( $user_id ) {\n\n if ( isset( $_POST['first_name'] ) )\n update_user_meta($user_id, 'first_name', $_POST['first_name']);\n\n}\n</code></pre>\n"
},
{
"answer_id": 232787,
"author": "stoi2m1",
"author_id": 10907,
"author_profile": "https://wordpress.stackexchange.com/users/10907",
"pm_score": 2,
"selected": true,
"text": "<p>Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table.</p>\n\n<p>use this:</p>\n\n<pre><code>add_action('woocommerce_order_status_completed', 'save_to_donors',10,1);\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>add_action('user_register', 'save_to_donors',10,1);\n</code></pre>\n\n<p>also change <code>$user_id</code> to <code>$order_id</code> as the parameter being passed into your function.</p>\n\n<p>You will need to make some changes to your function since now <code>$order_id</code> will be passed into your function instead of <code>$user_id</code>. You can use some of the following code to get the <code>$order</code> object and <code>$user_id</code> I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different.</p>\n\n<pre><code>$order = new WC_Order( $order_id );\n$user_id = $order->user_id;\n$billing_address = $order->get_billing_address();\n$billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page\n$shipping_address = $order->get_shipping_address();\n$shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page\n</code></pre>\n\n<p>Info on the use of this hook <a href=\"http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/\" rel=\"nofollow noreferrer\">woocommerce_order_status_completed</a><br>\nInfo on how to <a href=\"https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce\">get user id from order id</a></p>\n"
}
] |
2016/07/20
|
[
"https://wordpress.stackexchange.com/questions/232692",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98169/"
] |
I have to make several changes to a website, and I'm willing to setup a copy of the current one on a subdirectory, on the same server.
I.E. if my site is `www.example.com`, what I'm trying to do is to fully copy it to `www.example.com/new/`, make all the necessary modifications, then, once it is done, copy it back to the main directory.
I know that it is not a simple matter of moving files, I guess that this is a complex matter involving different file paths and database entries. I'd like to know how can I safely do it and it the whole process has to be done manually or if there are some automatic tools (i.e. plugins) that can help me doing it without mistakes.
|
Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table.
use this:
```
add_action('woocommerce_order_status_completed', 'save_to_donors',10,1);
```
instead of this:
```
add_action('user_register', 'save_to_donors',10,1);
```
also change `$user_id` to `$order_id` as the parameter being passed into your function.
You will need to make some changes to your function since now `$order_id` will be passed into your function instead of `$user_id`. You can use some of the following code to get the `$order` object and `$user_id` I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different.
```
$order = new WC_Order( $order_id );
$user_id = $order->user_id;
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page
```
Info on the use of this hook [woocommerce\_order\_status\_completed](http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/)
Info on how to [get user id from order id](https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce)
|
232,752 |
<p>I'm trying to write a little script within my <code>footer.php</code> (which I'll later transform into a plugin) that send two form fields to a custom table (<code>wp_newsletter</code>). I'm already sending the form and writing to the table correctly, but I don't know how I can send a success or fail message back to the user. My current code is as follows:</p>
<pre><code><form method="post">
<input type="text" name="user_name">Name
<input type="text" name="user_email">Email
<input type="submit">
<?php echo $message; ?>
</form>
<?php
global $wpdb;
$table = $wpdb->prefix . "newsletter";
$name = sanitize_text_field( $_POST["user_name"] );
$email = sanitize_email( $_POST["user_email"] );
$message = "";
if( isset($_POST["submit"]) ) {
if ( is_email($email) && isset($name)) {
if ( $wpdb->insert( $table, array("name" => $name, "email" => $email)) != false ) {
$message = "Your subscription was sent.";
}
}
else {
if ( !is_email($email) ) {
$message = "Invalid email address.";
} elseif ( !isset($name) ) {
$message = "The field name is mandatory.";
} else {
$message = "Both name and email fields are mandatory.";
}
}
} else {
$message = "Please, try again later.";
}
?>
<?php wp_footer(); ?>
</body>
</html>
</code></pre>
<p>I (think) am testing it right, accordingly to the <a href="https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row" rel="nofollow">$wpdb</a> docs which says that:</p>
<blockquote>
<p>This function returns false if the row could not be inserted.
Otherwise, it returns the number of affected rows (which will always
be 1).</p>
</blockquote>
|
[
{
"answer_id": 232760,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>When I realized that PHP is an acronym for \"PHP Hypertext Preprocessor\" -- emphasis on \"preprocessor\" -- I finally understood that I can't mix PHP and HTML and expect any kind of interactivity with the user. When a web page is served, the PHP creates the HTML and then the HTML is displayed by the browser. If the user does something the PHP must respond to, it <strong>must</strong> trigger a new PHP/HTML page to provide some sort of response. (An alternate would be to use AJAX to send data back and forth without loading a new page. Wordpress works well with AJAX and there are tutorials a google search away.)</p>\n\n<p>For a simple form like yours, I would use javascript for error checking. If the form is not filled in, prevent form submission with JS. If the form is complete, the form's action can be a .php file that does the database insert and displays the success/failure message in HTML.</p>\n"
},
{
"answer_id": 291324,
"author": "luke_mclachlan",
"author_id": 77800,
"author_profile": "https://wordpress.stackexchange.com/users/77800",
"pm_score": 0,
"selected": false,
"text": "<p>I came here via google and what helped me was using properties of $wpdb object:</p>\n\n<pre><code>$wpdb->last_error \n</code></pre>\n\n<p>shows the last error if present</p>\n\n<pre><code>$wpdb->last_query \n</code></pre>\n\n<p>shows the last query which gave the above error</p>\n"
},
{
"answer_id": 334203,
"author": "Hiren Siddhpura",
"author_id": 158734,
"author_profile": "https://wordpress.stackexchange.com/users/158734",
"pm_score": 3,
"selected": false,
"text": "<p>It returns either the number of rows inserted or false on error.</p>\n\n<p>Maybe you can get id of inserted recode or false if the insert fails:</p>\n\n<p><strong>refer link</strong>: <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/#return\" rel=\"noreferrer\">https://developer.wordpress.org/reference/classes/wpdb/insert/#return</a></p>\n\n<p>So you can check like below:</p>\n\n<pre><code>$result_check = $wpdb->insert( $table, array(\"name\" => $name, \"email\" => $email));\nif($result_check){\n //successfully inserted.\n}else{\n //something gone wrong\n}\n</code></pre>\n"
}
] |
2016/07/20
|
[
"https://wordpress.stackexchange.com/questions/232752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60070/"
] |
I'm trying to write a little script within my `footer.php` (which I'll later transform into a plugin) that send two form fields to a custom table (`wp_newsletter`). I'm already sending the form and writing to the table correctly, but I don't know how I can send a success or fail message back to the user. My current code is as follows:
```
<form method="post">
<input type="text" name="user_name">Name
<input type="text" name="user_email">Email
<input type="submit">
<?php echo $message; ?>
</form>
<?php
global $wpdb;
$table = $wpdb->prefix . "newsletter";
$name = sanitize_text_field( $_POST["user_name"] );
$email = sanitize_email( $_POST["user_email"] );
$message = "";
if( isset($_POST["submit"]) ) {
if ( is_email($email) && isset($name)) {
if ( $wpdb->insert( $table, array("name" => $name, "email" => $email)) != false ) {
$message = "Your subscription was sent.";
}
}
else {
if ( !is_email($email) ) {
$message = "Invalid email address.";
} elseif ( !isset($name) ) {
$message = "The field name is mandatory.";
} else {
$message = "Both name and email fields are mandatory.";
}
}
} else {
$message = "Please, try again later.";
}
?>
<?php wp_footer(); ?>
</body>
</html>
```
I (think) am testing it right, accordingly to the [$wpdb](https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row) docs which says that:
>
> This function returns false if the row could not be inserted.
> Otherwise, it returns the number of affected rows (which will always
> be 1).
>
>
>
|
It returns either the number of rows inserted or false on error.
Maybe you can get id of inserted recode or false if the insert fails:
**refer link**: <https://developer.wordpress.org/reference/classes/wpdb/insert/#return>
So you can check like below:
```
$result_check = $wpdb->insert( $table, array("name" => $name, "email" => $email));
if($result_check){
//successfully inserted.
}else{
//something gone wrong
}
```
|
232,759 |
<p>I'm trying to add an incremental variable to each post that comes up in a series of queries. The purpose is to calculate a weight for each result in order to be able to order everything later.</p>
<p>This is what I've come up with so far, but I'm doing something wrong, as the weights seem to add up globally instead of for each particular post.</p>
<pre><code>// set the variables
$author_id = get_the_author_meta('ID');
$tags_id = wp_get_post_tags($post->ID); $first_tag = $tags_id[0]->term_id;
$categories_id = wp_get_post_categories($post->ID);
$weight = 0;
// loop for same tag
$by_tag = new WP_Query(array(
'tag__in' => $first_tag,
'posts_per_page' => '5'
));
// attempting to assign values to posts - unsuccessfully
if ($by_tag):
foreach ($by_tag as $post):
setup_postdata($post->ID);
$weight += 2;
endforeach;
endif;
// add ids to array
if ( $by_tag->have_posts() ) {
while ( $by_tag->have_posts() ) {
$by_tag->the_post();
$add[] = get_the_id();
}}
// loop for same category
$by_category = new WP_Query(array(
'category__in' => $categories_id,
'posts_per_page' => '5'
));
// same as before
if ($by_category):
foreach ($by_category as $post):
setup_postdata($post->ID);
$weight += 1;
endforeach;
endif;
// add ids to array
if ( $by_category->have_posts() ) {
while ( $by_category->have_posts() ) {
$by_category->the_post();
$add[] = get_the_id();
}}
// loop array of combined results
$related = new WP_Query(array(
'post__in' => $add,
'post__not_in' => array($post->ID),
'orderby' => $weight,
'order' => 'DESC',
'posts_per_page' => '10'
));
// show them
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
// [template]
}}
</code></pre>
|
[
{
"answer_id": 232760,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>When I realized that PHP is an acronym for \"PHP Hypertext Preprocessor\" -- emphasis on \"preprocessor\" -- I finally understood that I can't mix PHP and HTML and expect any kind of interactivity with the user. When a web page is served, the PHP creates the HTML and then the HTML is displayed by the browser. If the user does something the PHP must respond to, it <strong>must</strong> trigger a new PHP/HTML page to provide some sort of response. (An alternate would be to use AJAX to send data back and forth without loading a new page. Wordpress works well with AJAX and there are tutorials a google search away.)</p>\n\n<p>For a simple form like yours, I would use javascript for error checking. If the form is not filled in, prevent form submission with JS. If the form is complete, the form's action can be a .php file that does the database insert and displays the success/failure message in HTML.</p>\n"
},
{
"answer_id": 291324,
"author": "luke_mclachlan",
"author_id": 77800,
"author_profile": "https://wordpress.stackexchange.com/users/77800",
"pm_score": 0,
"selected": false,
"text": "<p>I came here via google and what helped me was using properties of $wpdb object:</p>\n\n<pre><code>$wpdb->last_error \n</code></pre>\n\n<p>shows the last error if present</p>\n\n<pre><code>$wpdb->last_query \n</code></pre>\n\n<p>shows the last query which gave the above error</p>\n"
},
{
"answer_id": 334203,
"author": "Hiren Siddhpura",
"author_id": 158734,
"author_profile": "https://wordpress.stackexchange.com/users/158734",
"pm_score": 3,
"selected": false,
"text": "<p>It returns either the number of rows inserted or false on error.</p>\n\n<p>Maybe you can get id of inserted recode or false if the insert fails:</p>\n\n<p><strong>refer link</strong>: <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/#return\" rel=\"noreferrer\">https://developer.wordpress.org/reference/classes/wpdb/insert/#return</a></p>\n\n<p>So you can check like below:</p>\n\n<pre><code>$result_check = $wpdb->insert( $table, array(\"name\" => $name, \"email\" => $email));\nif($result_check){\n //successfully inserted.\n}else{\n //something gone wrong\n}\n</code></pre>\n"
}
] |
2016/07/20
|
[
"https://wordpress.stackexchange.com/questions/232759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70333/"
] |
I'm trying to add an incremental variable to each post that comes up in a series of queries. The purpose is to calculate a weight for each result in order to be able to order everything later.
This is what I've come up with so far, but I'm doing something wrong, as the weights seem to add up globally instead of for each particular post.
```
// set the variables
$author_id = get_the_author_meta('ID');
$tags_id = wp_get_post_tags($post->ID); $first_tag = $tags_id[0]->term_id;
$categories_id = wp_get_post_categories($post->ID);
$weight = 0;
// loop for same tag
$by_tag = new WP_Query(array(
'tag__in' => $first_tag,
'posts_per_page' => '5'
));
// attempting to assign values to posts - unsuccessfully
if ($by_tag):
foreach ($by_tag as $post):
setup_postdata($post->ID);
$weight += 2;
endforeach;
endif;
// add ids to array
if ( $by_tag->have_posts() ) {
while ( $by_tag->have_posts() ) {
$by_tag->the_post();
$add[] = get_the_id();
}}
// loop for same category
$by_category = new WP_Query(array(
'category__in' => $categories_id,
'posts_per_page' => '5'
));
// same as before
if ($by_category):
foreach ($by_category as $post):
setup_postdata($post->ID);
$weight += 1;
endforeach;
endif;
// add ids to array
if ( $by_category->have_posts() ) {
while ( $by_category->have_posts() ) {
$by_category->the_post();
$add[] = get_the_id();
}}
// loop array of combined results
$related = new WP_Query(array(
'post__in' => $add,
'post__not_in' => array($post->ID),
'orderby' => $weight,
'order' => 'DESC',
'posts_per_page' => '10'
));
// show them
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
// [template]
}}
```
|
It returns either the number of rows inserted or false on error.
Maybe you can get id of inserted recode or false if the insert fails:
**refer link**: <https://developer.wordpress.org/reference/classes/wpdb/insert/#return>
So you can check like below:
```
$result_check = $wpdb->insert( $table, array("name" => $name, "email" => $email));
if($result_check){
//successfully inserted.
}else{
//something gone wrong
}
```
|
232,774 |
<p>I'm displaying the current user's info on the front-end, but haven't been able to locate the correct hook for the bio, other than as an "author" hook. Help?</p>
|
[
{
"answer_id": 232778,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>You probably want to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow\"><code>wp_get_current_user</code></a> to find out which user is browsing the site.</p>\n\n<pre><code>$current_user = wp_get_current_user();\n\necho 'User ID: ' . $current_user->ID . '<br />';\n</code></pre>\n\n<p>From there you'll use the <code>ID</code> to pull the user's metadata with <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\"><code>get_user_meta</code></a>.</p>\n\n<pre><code>$all_meta_for_user = get_user_meta( $current_user->ID );\n\necho 'User Description: ' . $all_meta_for_user['description'] . '<br />';\n</code></pre>\n\n<p>The <code>description</code> key is probably what you're after.</p>\n\n<hr>\n\n<p>As you pointed out, the <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-user.php\" rel=\"nofollow\"><code>WP_User</code></a> already includes a few fields on it which may be duplicated in the user_meta, including <code>$current_user->description</code>.</p>\n\n<pre><code> /**\n11 * Core class used to implement the WP_User object.\n12 *\n13 * @since 2.0.0\n14 *\n15 * @property string $nickname\n16 * @property string $description\n17 * @property string $user_description\n18 * @property string $first_name\n19 * @property string $user_firstname\n20 * @property string $last_name\n21 * @property string $user_lastname\n22 * @property string $user_login\n23 * @property string $user_pass\n24 * @property string $user_nicename\n25 * @property string $user_email\n26 * @property string $user_url\n27 * @property string $user_registered\n28 * @property string $user_activation_key\n29 * @property string $user_status\n30 * @property string $display_name\n31 * @property string $spam\n32 * @property string $deleted\n33 */\n</code></pre>\n"
},
{
"answer_id": 232779,
"author": "Laura Sage",
"author_id": 88351,
"author_profile": "https://wordpress.stackexchange.com/users/88351",
"pm_score": 0,
"selected": false,
"text": "<p>A-ha! I was already getting the rest of the current user info, but needed the proper \"echo\" line to get that biographical info field. Didn't realize it was called \"description\". So your code put me on the right path. All I needed to add to what I already had was:</p>\n\n<pre><code>echo 'User Description: ' . $current_user->description . '<br />';\n</code></pre>\n\n<p>Thank you muchly!</p>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232774",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88351/"
] |
I'm displaying the current user's info on the front-end, but haven't been able to locate the correct hook for the bio, other than as an "author" hook. Help?
|
You probably want to use [`wp_get_current_user`](https://codex.wordpress.org/Function_Reference/wp_get_current_user) to find out which user is browsing the site.
```
$current_user = wp_get_current_user();
echo 'User ID: ' . $current_user->ID . '<br />';
```
From there you'll use the `ID` to pull the user's metadata with [`get_user_meta`](https://codex.wordpress.org/Function_Reference/get_user_meta).
```
$all_meta_for_user = get_user_meta( $current_user->ID );
echo 'User Description: ' . $all_meta_for_user['description'] . '<br />';
```
The `description` key is probably what you're after.
---
As you pointed out, the [`WP_User`](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-user.php) already includes a few fields on it which may be duplicated in the user\_meta, including `$current_user->description`.
```
/**
11 * Core class used to implement the WP_User object.
12 *
13 * @since 2.0.0
14 *
15 * @property string $nickname
16 * @property string $description
17 * @property string $user_description
18 * @property string $first_name
19 * @property string $user_firstname
20 * @property string $last_name
21 * @property string $user_lastname
22 * @property string $user_login
23 * @property string $user_pass
24 * @property string $user_nicename
25 * @property string $user_email
26 * @property string $user_url
27 * @property string $user_registered
28 * @property string $user_activation_key
29 * @property string $user_status
30 * @property string $display_name
31 * @property string $spam
32 * @property string $deleted
33 */
```
|
232,796 |
<p>Having a few issues getting things to work after changing wordpress from http to https on a windows sever. The web.config file is a bit of a mare to work with and the hosting company seems to think that changing http to https in wordpress settings is the only change necessary. currently I can only get the site to load css/js files on any pages other than the homepage by using default permalinks. and when I try adding http to https redirects in the web-config it causes even more problems. I've exhausted google so any advice appreciated.</p>
|
[
{
"answer_id": 232778,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>You probably want to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow\"><code>wp_get_current_user</code></a> to find out which user is browsing the site.</p>\n\n<pre><code>$current_user = wp_get_current_user();\n\necho 'User ID: ' . $current_user->ID . '<br />';\n</code></pre>\n\n<p>From there you'll use the <code>ID</code> to pull the user's metadata with <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\"><code>get_user_meta</code></a>.</p>\n\n<pre><code>$all_meta_for_user = get_user_meta( $current_user->ID );\n\necho 'User Description: ' . $all_meta_for_user['description'] . '<br />';\n</code></pre>\n\n<p>The <code>description</code> key is probably what you're after.</p>\n\n<hr>\n\n<p>As you pointed out, the <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-user.php\" rel=\"nofollow\"><code>WP_User</code></a> already includes a few fields on it which may be duplicated in the user_meta, including <code>$current_user->description</code>.</p>\n\n<pre><code> /**\n11 * Core class used to implement the WP_User object.\n12 *\n13 * @since 2.0.0\n14 *\n15 * @property string $nickname\n16 * @property string $description\n17 * @property string $user_description\n18 * @property string $first_name\n19 * @property string $user_firstname\n20 * @property string $last_name\n21 * @property string $user_lastname\n22 * @property string $user_login\n23 * @property string $user_pass\n24 * @property string $user_nicename\n25 * @property string $user_email\n26 * @property string $user_url\n27 * @property string $user_registered\n28 * @property string $user_activation_key\n29 * @property string $user_status\n30 * @property string $display_name\n31 * @property string $spam\n32 * @property string $deleted\n33 */\n</code></pre>\n"
},
{
"answer_id": 232779,
"author": "Laura Sage",
"author_id": 88351,
"author_profile": "https://wordpress.stackexchange.com/users/88351",
"pm_score": 0,
"selected": false,
"text": "<p>A-ha! I was already getting the rest of the current user info, but needed the proper \"echo\" line to get that biographical info field. Didn't realize it was called \"description\". So your code put me on the right path. All I needed to add to what I already had was:</p>\n\n<pre><code>echo 'User Description: ' . $current_user->description . '<br />';\n</code></pre>\n\n<p>Thank you muchly!</p>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232796",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98674/"
] |
Having a few issues getting things to work after changing wordpress from http to https on a windows sever. The web.config file is a bit of a mare to work with and the hosting company seems to think that changing http to https in wordpress settings is the only change necessary. currently I can only get the site to load css/js files on any pages other than the homepage by using default permalinks. and when I try adding http to https redirects in the web-config it causes even more problems. I've exhausted google so any advice appreciated.
|
You probably want to use [`wp_get_current_user`](https://codex.wordpress.org/Function_Reference/wp_get_current_user) to find out which user is browsing the site.
```
$current_user = wp_get_current_user();
echo 'User ID: ' . $current_user->ID . '<br />';
```
From there you'll use the `ID` to pull the user's metadata with [`get_user_meta`](https://codex.wordpress.org/Function_Reference/get_user_meta).
```
$all_meta_for_user = get_user_meta( $current_user->ID );
echo 'User Description: ' . $all_meta_for_user['description'] . '<br />';
```
The `description` key is probably what you're after.
---
As you pointed out, the [`WP_User`](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-user.php) already includes a few fields on it which may be duplicated in the user\_meta, including `$current_user->description`.
```
/**
11 * Core class used to implement the WP_User object.
12 *
13 * @since 2.0.0
14 *
15 * @property string $nickname
16 * @property string $description
17 * @property string $user_description
18 * @property string $first_name
19 * @property string $user_firstname
20 * @property string $last_name
21 * @property string $user_lastname
22 * @property string $user_login
23 * @property string $user_pass
24 * @property string $user_nicename
25 * @property string $user_email
26 * @property string $user_url
27 * @property string $user_registered
28 * @property string $user_activation_key
29 * @property string $user_status
30 * @property string $display_name
31 * @property string $spam
32 * @property string $deleted
33 */
```
|
232,802 |
<p>I just want to remove <strong>Comment's column</strong> in <strong>all post-types</strong> and in a <strong>single function</strong></p>
<p><a href="https://i.stack.imgur.com/xUdLd.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xUdLd.gif" alt="enter image description here"></a></p>
<p><strong>My current function , Have to do each post-type like this :</strong></p>
<pre><code>function remove_post_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-post_columns','remove_post_columns',10,1);
function remove_page_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-page_columns','remove_page_columns',10,1);
</code></pre>
<p><strong>Possible to do in a single function</strong> and for future post-types ?</p>
|
[
{
"answer_id": 232803,
"author": "l2aelba",
"author_id": 6332,
"author_profile": "https://wordpress.stackexchange.com/users/6332",
"pm_score": 3,
"selected": true,
"text": "<p><strong>I got an alternative :</strong></p>\n\n<p><em>This will not just hiding but disabling also</em></p>\n\n<pre><code>function disable_comments() {\n $post_types = get_post_types();\n foreach ($post_types as $post_type) {\n if(post_type_supports($post_type,'comments')) {\n remove_post_type_support($post_type,'comments');\n remove_post_type_support($post_type,'trackbacks');\n }\n }\n}\nadd_action('admin_init','disable_comments');\n</code></pre>\n"
},
{
"answer_id": 232804,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>If you change <code>manage_edit-post_columns</code> to <code>manage_posts_columns</code> in your code snippet, then it should hide the <em>comment</em> column for all post types (appart from the <code>page</code> post type) within the <code>WP_Posts_List_Table</code> <sup><a href=\"https://github.com/WordPress/WordPress/blob/04319a7898343be862034ae61f2428a78d57bb8e/wp-admin/includes/class-wp-posts-list-table.php#L593\" rel=\"nofollow\">src</a></sup>. You might want to check if the <code>column</code> array key isset first, before unsetting it.</p>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6332/"
] |
I just want to remove **Comment's column** in **all post-types** and in a **single function**
[](https://i.stack.imgur.com/xUdLd.gif)
**My current function , Have to do each post-type like this :**
```
function remove_post_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-post_columns','remove_post_columns',10,1);
function remove_page_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-page_columns','remove_page_columns',10,1);
```
**Possible to do in a single function** and for future post-types ?
|
**I got an alternative :**
*This will not just hiding but disabling also*
```
function disable_comments() {
$post_types = get_post_types();
foreach ($post_types as $post_type) {
if(post_type_supports($post_type,'comments')) {
remove_post_type_support($post_type,'comments');
remove_post_type_support($post_type,'trackbacks');
}
}
}
add_action('admin_init','disable_comments');
```
|
232,809 |
<p>Hello I have code intended to get the most viewed post for last 2 days and it seems like not working or maybe my code is just incorrect. I appreciate any help. Thanks.</p>
<pre><code> $args = array(
'post_type' => 'post',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '2 days ago',
)
)
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul class="posts-list">';
while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
<div class="content">
<time datetime="<?php echo get_the_date(DATE_W3C); ?>"><?php the_time('d, F Y') ?></time>
<span class="comments">
<a href="<?php comments_link(); ?>" class="comments"><i class="fa fa-comments-o"></i> <?php echo get_comments_number(); ?></a>
</span>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title();?></a>
</div>
</li>
<?php }
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
</code></pre>
|
[
{
"answer_id": 232987,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 0,
"selected": false,
"text": "<p>Try adjusting your <code>$args</code>. You will need to get the date from two days ago and then pass the year, month and day into the after argument as an array. </p>\n\n<p>Try this:</p>\n\n<pre><code>$date = strtotime ( '-2 day' ); // Date from two days ago\n\n$args = array(\n 'post_type' => 'post',\n 'meta_key' => 'post_views_count',\n 'orderby' => 'meta_value_num',\n 'date_query' => array(\n array(\n 'after' => array(\n 'year' => date('Y', $date ),\n 'month' => date('m', $date ),\n 'day' => date('d', $date ),\n ),\n )\n )\n);\n</code></pre>\n\n<p>More documentation about <code>WP_Query</code> and its arguments, including <code>date_query</code> can be found <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 300836,
"author": "Shameem Ali",
"author_id": 137710,
"author_profile": "https://wordpress.stackexchange.com/users/137710",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue. I had searched many times for this issue. but I could not find a solution for this. </p>\n\n<blockquote>\n <p>get the most viewed post for the last 2 days not to get the posts for the last 2 days</p>\n</blockquote>\n\n<p>I have a table named \"wp_popularpostssummary\".</p>\n\n<p><a href=\"https://i.stack.imgur.com/pAbjS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pAbjS.png\" alt=\"enter image description here\"></a></p>\n\n<p>Result ll be </p>\n\n<p><a href=\"https://i.stack.imgur.com/eI1f9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eI1f9.png\" alt=\"enter image description here\"></a></p>\n\n<p>so from this table get result postids by using following custom query </p>\n\n<pre><code>$results = $wpdb->get_results($wpdb->prepare('SELECT postid,COUNT(*) AS qy FROM `wp_popularpostssummary` WHERE `view_date` BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE() GROUP BY postid ORDER BY qy DESC'));\n</code></pre>\n\n<p>query result ll be the post id's of most viewed posts for the last one week. \nthen using following foreach loop to get post id</p>\n\n<pre><code> $pids = [];\n\n $results = json_decode(json_encode($results), true);\n\n foreach ($results as $result) {\n foreach ($result as $k => $v) {\n if($k == 'postid'){\n array_push($pids, $v);\n }\n };\n\n }\n</code></pre>\n\n<p>finally, use post id to fetch post details. code ll be following</p>\n\n<pre><code> $args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page' => '10',\n 'orderby' => 'post__in',\n 'post__in' => $pids\n\n );\n\n\n $query = new WP_Query( $args ); if ( $query->have_posts() ) {\n // The Loop\n while ( $query->have_posts() ) { //code here\n }\n }\n</code></pre>\n\n<p>Change date duration according to you needs.\nI hope this ll help to anyone in the feature!<br>\nLet me know if have a query.</p>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232809",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98686/"
] |
Hello I have code intended to get the most viewed post for last 2 days and it seems like not working or maybe my code is just incorrect. I appreciate any help. Thanks.
```
$args = array(
'post_type' => 'post',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '2 days ago',
)
)
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul class="posts-list">';
while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
<div class="content">
<time datetime="<?php echo get_the_date(DATE_W3C); ?>"><?php the_time('d, F Y') ?></time>
<span class="comments">
<a href="<?php comments_link(); ?>" class="comments"><i class="fa fa-comments-o"></i> <?php echo get_comments_number(); ?></a>
</span>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title();?></a>
</div>
</li>
<?php }
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
```
|
I had the same issue. I had searched many times for this issue. but I could not find a solution for this.
>
> get the most viewed post for the last 2 days not to get the posts for the last 2 days
>
>
>
I have a table named "wp\_popularpostssummary".
[](https://i.stack.imgur.com/pAbjS.png)
Result ll be
[](https://i.stack.imgur.com/eI1f9.png)
so from this table get result postids by using following custom query
```
$results = $wpdb->get_results($wpdb->prepare('SELECT postid,COUNT(*) AS qy FROM `wp_popularpostssummary` WHERE `view_date` BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE() GROUP BY postid ORDER BY qy DESC'));
```
query result ll be the post id's of most viewed posts for the last one week.
then using following foreach loop to get post id
```
$pids = [];
$results = json_decode(json_encode($results), true);
foreach ($results as $result) {
foreach ($result as $k => $v) {
if($k == 'postid'){
array_push($pids, $v);
}
};
}
```
finally, use post id to fetch post details. code ll be following
```
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '10',
'orderby' => 'post__in',
'post__in' => $pids
);
$query = new WP_Query( $args ); if ( $query->have_posts() ) {
// The Loop
while ( $query->have_posts() ) { //code here
}
}
```
Change date duration according to you needs.
I hope this ll help to anyone in the feature!
Let me know if have a query.
|
232,818 |
<p>after migrating my WP site to a different domain and making adjustments, Font Awesome stopped showing icons and shows some weird text instead, for example & # 61505; (I can't copy it as a text, looks like an automatically generated graphics).</p>
<p>Please see attached image.
<a href="https://i.stack.imgur.com/WsuFB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WsuFB.png" alt="enter image description here"></a></p>
<p>Any help?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 232987,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 0,
"selected": false,
"text": "<p>Try adjusting your <code>$args</code>. You will need to get the date from two days ago and then pass the year, month and day into the after argument as an array. </p>\n\n<p>Try this:</p>\n\n<pre><code>$date = strtotime ( '-2 day' ); // Date from two days ago\n\n$args = array(\n 'post_type' => 'post',\n 'meta_key' => 'post_views_count',\n 'orderby' => 'meta_value_num',\n 'date_query' => array(\n array(\n 'after' => array(\n 'year' => date('Y', $date ),\n 'month' => date('m', $date ),\n 'day' => date('d', $date ),\n ),\n )\n )\n);\n</code></pre>\n\n<p>More documentation about <code>WP_Query</code> and its arguments, including <code>date_query</code> can be found <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 300836,
"author": "Shameem Ali",
"author_id": 137710,
"author_profile": "https://wordpress.stackexchange.com/users/137710",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue. I had searched many times for this issue. but I could not find a solution for this. </p>\n\n<blockquote>\n <p>get the most viewed post for the last 2 days not to get the posts for the last 2 days</p>\n</blockquote>\n\n<p>I have a table named \"wp_popularpostssummary\".</p>\n\n<p><a href=\"https://i.stack.imgur.com/pAbjS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pAbjS.png\" alt=\"enter image description here\"></a></p>\n\n<p>Result ll be </p>\n\n<p><a href=\"https://i.stack.imgur.com/eI1f9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eI1f9.png\" alt=\"enter image description here\"></a></p>\n\n<p>so from this table get result postids by using following custom query </p>\n\n<pre><code>$results = $wpdb->get_results($wpdb->prepare('SELECT postid,COUNT(*) AS qy FROM `wp_popularpostssummary` WHERE `view_date` BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE() GROUP BY postid ORDER BY qy DESC'));\n</code></pre>\n\n<p>query result ll be the post id's of most viewed posts for the last one week. \nthen using following foreach loop to get post id</p>\n\n<pre><code> $pids = [];\n\n $results = json_decode(json_encode($results), true);\n\n foreach ($results as $result) {\n foreach ($result as $k => $v) {\n if($k == 'postid'){\n array_push($pids, $v);\n }\n };\n\n }\n</code></pre>\n\n<p>finally, use post id to fetch post details. code ll be following</p>\n\n<pre><code> $args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page' => '10',\n 'orderby' => 'post__in',\n 'post__in' => $pids\n\n );\n\n\n $query = new WP_Query( $args ); if ( $query->have_posts() ) {\n // The Loop\n while ( $query->have_posts() ) { //code here\n }\n }\n</code></pre>\n\n<p>Change date duration according to you needs.\nI hope this ll help to anyone in the feature!<br>\nLet me know if have a query.</p>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232818",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98690/"
] |
after migrating my WP site to a different domain and making adjustments, Font Awesome stopped showing icons and shows some weird text instead, for example & # 61505; (I can't copy it as a text, looks like an automatically generated graphics).
Please see attached image.
[](https://i.stack.imgur.com/WsuFB.png)
Any help?
Thanks!
|
I had the same issue. I had searched many times for this issue. but I could not find a solution for this.
>
> get the most viewed post for the last 2 days not to get the posts for the last 2 days
>
>
>
I have a table named "wp\_popularpostssummary".
[](https://i.stack.imgur.com/pAbjS.png)
Result ll be
[](https://i.stack.imgur.com/eI1f9.png)
so from this table get result postids by using following custom query
```
$results = $wpdb->get_results($wpdb->prepare('SELECT postid,COUNT(*) AS qy FROM `wp_popularpostssummary` WHERE `view_date` BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE() GROUP BY postid ORDER BY qy DESC'));
```
query result ll be the post id's of most viewed posts for the last one week.
then using following foreach loop to get post id
```
$pids = [];
$results = json_decode(json_encode($results), true);
foreach ($results as $result) {
foreach ($result as $k => $v) {
if($k == 'postid'){
array_push($pids, $v);
}
};
}
```
finally, use post id to fetch post details. code ll be following
```
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '10',
'orderby' => 'post__in',
'post__in' => $pids
);
$query = new WP_Query( $args ); if ( $query->have_posts() ) {
// The Loop
while ( $query->have_posts() ) { //code here
}
}
```
Change date duration according to you needs.
I hope this ll help to anyone in the feature!
Let me know if have a query.
|
232,826 |
<p>I have a form on a page that search property with a location field and I used the following meta query to process the search;</p>
<pre><code>$location = preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
$meta_query = array( 'relation' => 'AND' );
if($location) {
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => 'property_country',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_city',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_location',
'value' => $location,
'compare' => 'LIKE'
)
);
}
</code></pre>
<p>However, it works fine if I search for <em>New</em> but returns no results if I search for <em>New York</em>. How can I resolve this? Is there a way to add a wildcard before and after the <code>$location</code>? I tried adding <code>'*'.$location.'*'</code> but that did nothing.</p>
|
[
{
"answer_id": 232828,
"author": "FaCE",
"author_id": 96768,
"author_profile": "https://wordpress.stackexchange.com/users/96768",
"pm_score": 2,
"selected": false,
"text": "<p>Have you <code>var_dump</code>ed <code>$location</code>?</p>\n\n<p><code>WP_Query</code>'s <code>meta_query</code> uses the class <code>WP_Meta_Query</code>, which automatically appends and prepends '%' to any <em>string</em> passed to it:</p>\n\n<pre><code>// From wp-includes/class-wp-meta-query.php:610 \nswitch ( $meta_compare ) {\n // ...\n case 'LIKE' :\n case 'NOT LIKE' :\n $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';\n $where = $wpdb->prepare( '%s', $meta_value );\n break;\n // ...\n}\n</code></pre>\n\n<p>So maybe try using <code>(string) $location</code> as the sql statement is prepared, and expecting a string -- that's what the <code>%s</code> means in the line <code>$where = $wpdb->prepare( '%s', $meta_value );</code>. You can cast your variable to a string like this:</p>\n\n<pre><code>$location = (string) preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);\n</code></pre>\n"
},
{
"answer_id": 232930,
"author": "FaCE",
"author_id": 96768,
"author_profile": "https://wordpress.stackexchange.com/users/96768",
"pm_score": 1,
"selected": false,
"text": "<p>Try joining the string with wildcards:</p>\n\n<pre><code>$location = implode('%', explode($location, ' '));\n</code></pre>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36773/"
] |
I have a form on a page that search property with a location field and I used the following meta query to process the search;
```
$location = preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
$meta_query = array( 'relation' => 'AND' );
if($location) {
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => 'property_country',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_city',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_location',
'value' => $location,
'compare' => 'LIKE'
)
);
}
```
However, it works fine if I search for *New* but returns no results if I search for *New York*. How can I resolve this? Is there a way to add a wildcard before and after the `$location`? I tried adding `'*'.$location.'*'` but that did nothing.
|
Have you `var_dump`ed `$location`?
`WP_Query`'s `meta_query` uses the class `WP_Meta_Query`, which automatically appends and prepends '%' to any *string* passed to it:
```
// From wp-includes/class-wp-meta-query.php:610
switch ( $meta_compare ) {
// ...
case 'LIKE' :
case 'NOT LIKE' :
$meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
$where = $wpdb->prepare( '%s', $meta_value );
break;
// ...
}
```
So maybe try using `(string) $location` as the sql statement is prepared, and expecting a string -- that's what the `%s` means in the line `$where = $wpdb->prepare( '%s', $meta_value );`. You can cast your variable to a string like this:
```
$location = (string) preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
```
|
232,873 |
<p>I created a page template to list all products of a specific product line.
Now I want to list all posts from this custom post type (products) based on the taxonomy described in the shortcode for each page.</p>
<p>Example:</p>
<p>Page "List of all Prime products"</p>
<p>[products line="prime"]</p>
<p>I tried this code:</p>
<pre><code>function shortcode_mostra_produtos ( $atts ) {
$atts = shortcode_atts( array(
'default' => ''
), $atts );
$terms = get_terms('linhas');
wp_reset_query();
$args = array('post_type' => 'produtos',
'tax_query' => array(
array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => $atts,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
echo ' "'.get_the_title().'" ';
endwhile;
}
}
add_shortcode( 'produtos','shortcode_mostra_produtos' );
</code></pre>
|
[
{
"answer_id": 232879,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": true,
"text": "<p>First off, it's always good to register shortcode during <code>init</code> versus just in your general <code>functions.php</code> file. At the very least <code>add_shortcode()</code> should be in <code>init</code>. Anyway, let's begin!</p>\n\n<p>Whenever you use <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"noreferrer\"><code>add_shortcode()</code></a> the first parameter is going to be the name of the shortcode and the 2nd will be the callback function. This means that:</p>\n\n<pre><code>[products line=\"prime\"]\n</code></pre>\n\n<p>Should be instead:</p>\n\n<pre><code>[produtos line=\"prime\"]\n</code></pre>\n\n<p>So far we have this:</p>\n\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n\n/**\n * Produtos Shortcode Callback\n * - [produtos]\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n /** Our outline will go here\n}\n</code></pre>\n\n<p>Let's take a look at processing attributes. The way <a href=\"https://codex.wordpress.org/Function_Reference/shortcode_atts\" rel=\"noreferrer\"><code>shortcode_atts()</code></a> works is that it will try to match attributes passed to the shortcode with attributes in the passed array, left side being the key and the right side being the defaults. So we need to change <code>defaults</code> to <code>line</code> instead - if we want to default to a category, this would be the place:</p>\n\n<pre><code>$atts = shortcode_atts( array(\n 'line' => ''\n), $atts );\n</code></pre>\n\n<p>IF the user adds a attribute to the shortcode <code>line=\"test\"</code> then our array index <code>line</code> will hold <code>test</code>: </p>\n\n<pre><code>echo $atts['line']; // Prints 'test'\n</code></pre>\n\n<p>All other attributes will be ignored unless we add them to the <code>shortcode_atts()</code> array. Finally it's just the WP_Query and printing what you need:</p>\n\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n\n/**\n * Produtos Shortcode Callback\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n global $wp_query,\n $post;\n\n $atts = shortcode_atts( array(\n 'line' => ''\n ), $atts );\n\n $loop = new WP_Query( array(\n 'posts_per_page' => 200,\n 'post_type' => 'produtos',\n 'orderby' => 'menu_order title',\n 'order' => 'ASC',\n 'tax_query' => array( array(\n 'taxonomy' => 'linhas',\n 'field' => 'slug',\n 'terms' => array( sanitize_title( $atts['line'] ) )\n ) )\n ) );\n\n if( ! $loop->have_posts() ) {\n return false;\n }\n\n while( $loop->have_posts() ) {\n $loop->the_post();\n echo the_title();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 270652,
"author": "Vivek Tamrakar",
"author_id": 96956,
"author_profile": "https://wordpress.stackexchange.com/users/96956",
"pm_score": -1,
"selected": false,
"text": "<p>**Try this **</p>\n\n<pre><code>function shortcode_bws_quiz_maker($id)\n{\n if($id!='')\n {\n $post_id=$id[0];\n $html='';\n global $wpdb;\n $args=array('post_type'=>'post_type','p'=>$post_id);\n $wp_posts=new WP_Query($args);\n $posts=$wp_posts->posts;\n $html.=\"What you to get write here\";\n return $html;\n\n }\n else\n {\n return 'Please enter correct shortcode'; \n }\n\n}\nadd_shortcode('bws_quiz_maker','shortcode_bws_quiz_maker');\n</code></pre>\n"
},
{
"answer_id": 318370,
"author": "Pradeep",
"author_id": 145348,
"author_profile": "https://wordpress.stackexchange.com/users/145348",
"pm_score": 0,
"selected": false,
"text": "<pre><code> add_shortcode( 'product-list','bpo_product_list' );\nfunction bpo_product_list ( $atts ) {\n $atts = shortcode_atts( array(\n 'category' => ''\n ), $atts );\n $terms = get_terms('product_category');\n wp_reset_query();\n $args = array('post_type' => 'product',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_category',\n 'field' => 'slug',\n 'terms' => $atts,\n ),\n ),\n );\n $loop = new WP_Query($args);\n if($loop->have_posts()) {\n while($loop->have_posts()) : $loop->the_post();\n echo ' \"'.get_the_title().'\" ';\n endwhile;\n }\n\n else {\n echo 'Sorry, no posts were found';\n }\n}\n</code></pre>\n\n<p>In above code, I have created product CPT and product_category taxonomy for product CPT. </p>\n\n<p>[product-list category=\"shirts\"]</p>\n\n<p>The above code is perfectly works!</p>\n"
}
] |
2016/07/21
|
[
"https://wordpress.stackexchange.com/questions/232873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98722/"
] |
I created a page template to list all products of a specific product line.
Now I want to list all posts from this custom post type (products) based on the taxonomy described in the shortcode for each page.
Example:
Page "List of all Prime products"
[products line="prime"]
I tried this code:
```
function shortcode_mostra_produtos ( $atts ) {
$atts = shortcode_atts( array(
'default' => ''
), $atts );
$terms = get_terms('linhas');
wp_reset_query();
$args = array('post_type' => 'produtos',
'tax_query' => array(
array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => $atts,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
echo ' "'.get_the_title().'" ';
endwhile;
}
}
add_shortcode( 'produtos','shortcode_mostra_produtos' );
```
|
First off, it's always good to register shortcode during `init` versus just in your general `functions.php` file. At the very least `add_shortcode()` should be in `init`. Anyway, let's begin!
Whenever you use [`add_shortcode()`](https://codex.wordpress.org/Function_Reference/add_shortcode) the first parameter is going to be the name of the shortcode and the 2nd will be the callback function. This means that:
```
[products line="prime"]
```
Should be instead:
```
[produtos line="prime"]
```
So far we have this:
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
* - [produtos]
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
/** Our outline will go here
}
```
Let's take a look at processing attributes. The way [`shortcode_atts()`](https://codex.wordpress.org/Function_Reference/shortcode_atts) works is that it will try to match attributes passed to the shortcode with attributes in the passed array, left side being the key and the right side being the defaults. So we need to change `defaults` to `line` instead - if we want to default to a category, this would be the place:
```
$atts = shortcode_atts( array(
'line' => ''
), $atts );
```
IF the user adds a attribute to the shortcode `line="test"` then our array index `line` will hold `test`:
```
echo $atts['line']; // Prints 'test'
```
All other attributes will be ignored unless we add them to the `shortcode_atts()` array. Finally it's just the WP\_Query and printing what you need:
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
global $wp_query,
$post;
$atts = shortcode_atts( array(
'line' => ''
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 200,
'post_type' => 'produtos',
'orderby' => 'menu_order title',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['line'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
}
wp_reset_postdata();
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.